2013-03-25 7 views
5

Sto tentando di accedere a TempData in Javascript. ma ottenendo valore nullo. Sto effettuando una chiamata ajax per aggiornare il record e voglio visualizzare il messaggio di registrazione aggiornato correttamente. che verrà dall'azione UpdateOperation dal controller. ma attualmente mostrerà il valore nullo. Ho anche controllare con Firebug mostra come segue:accesso tempdata in javascript in mvc4

function onComplete(e) { 

if (e.name == "update") { 

alert(''); 

} 

Ecco il mio codice di controllo

public class OperationController : BaseController 
    { 
     /// <summary> 
     /// Index action will return template view of the page without data 
     /// </summary> 
     /// <returns>Blank Action</returns> 
     public ActionResult Index() 
     { 
      return this.View(); 
     } 

     /// <summary> 
     /// Get all Operation from System 
     /// </summary> 
     /// <returns>return action result</returns> 
     [GridAction] 
     public ActionResult SelectOperation() 
     { 
      IEnumerable<OperationEntity> operationList = OperationComponent.GetAll(); 
      return this.View(new GridModel(operationList)); 
     } 

     /// <summary> 
     /// Method for update operation 
     /// </summary> 
     /// <param name="entity">moduleViewModel to update Module</param> 
     /// <returns>return action result</returns> 
     [GridAction] 
     public ActionResult UpdateOperation(OperationEntity entity) 
     { 
      if (ModelState.IsValid) 
      { 
       entity.Log = new BusinessCore.BusinessEntities.LogDetails(); 
       entity.Log.ModifiedBy = SessionHelper.UserId; 
       Status status = OperationComponent.Update(entity); 
       this.TempData["AlertMessage"] = status.Message; 
       this.ViewData["_AlertMessage"] = status.Message; 
       return this.View(new GridModel(OperationComponent.GetAll())); 
      } 
      else 
      { 
       return this.View(entity); 
      } 
     } 
    } 

A mio avviso

@using Telerik.Web.Mvc.UI; 
@{ 
    ViewBag.Title = "Operation List"; 
} 

<h2>@ViewBag.Title</h2> 
<script src="../../../../Scripts/jquery-1.7.1.min.js" type="text/javascript"></script> 
<script type="text/javascript"> 
// function onSave(e) { 
//  alert('Record Save Succesfully'); 
// } 
    function onComplete(e) { 
     if (e.name == "update") { 
      alert('@TempData["AlertMessage"]'); 
      alert('@ViewData["_AlertMessage"]'); 
     } 
     if (e.name == "insert") { 
      alert("Operation Inserted Successfully"); 
     } 
     if (e.name == "delete") { 
      alert("Operation Deleted Successfully"); 
     } 
    } 
    function newAlert(type, message) { 
    if (message != "" || message != null) { 
     $("#alert-area").append($("<div class='alert alert-success " + type + " fade in' data-alert><p><b> " + message + " </b></p></div>")); 
     $(".alert-success").delay(4000).fadeOut("slow", function() { $(this).remove(); }); 
    } 
} 
</script> 

@(Html.Telerik().Grid<QuexstERP.BusinessCore.BusinessEntities.SysAdmin.OperationEntity>() 
     .Name("Grid") 
     .DataKeys(keys => 
     { 
      keys.Add(p => p.Id); 
     }) 
        .ToolBar(commands => commands.Insert().ButtonType(GridButtonType.Image).ImageHtmlAttributes(new { style = "margin-left:0", title = "Add" })) 
     .DataBinding(dataBinding => 
     { 
      dataBinding.Ajax() 
       .Select("SelectOperation", "Operation") 
       .Insert("InsertOperation", "Operation") 
       .Update("UpdateOperation", "Operation") 
       .Delete("DeleteOperation", "Operation"); 
     }) 
     .Columns(columns => 
     { 
      columns.Command(commands => 
      { 
       commands.Edit().ButtonType(GridButtonType.Image).HtmlAttributes(new { title = "Edit" }); 
       commands.Delete().ButtonType(GridButtonType.Image).HtmlAttributes(new { title = "Delete" }); 
      }).Width(80).Title("Commands"); 
      columns.Bound(p => p.Name).Width(200).Title("Operation Name"); 
      columns.Bound(p => p.Description).Width(310).Title("Description"); 
     }) 
     .ClientEvents(events => events 
       .OnComplete("onComplete") 
       ) 
        .Editable(editing => editing.Mode(GridEditMode.PopUp).InsertRowPosition(GridInsertRowPosition.Top)) 

     .Pageable() 
     .Scrollable() 
     .Sortable() 
     .Filterable()   
) 
@section HeadContent { 
<style type="text/css"> 
    .field-validation-error 
    { 
     position: absolute; 
     display: block; 
    } 

    * html .field-validation-error { position: relative; } 
    *+html .field-validation-error { position: relative; } 

    .field-validation-error span 
    { 
     position: relative; 
     white-space: nowrap; 
     color: red; 
     padding: 10px 5px 3px; 
     background: transparent url('@Url.Content("~/Content/Common/validation-error-message.png") ') no-repeat 0 0; 
    } 

    /* in-form editing */ 
    .t-edit-form-container 
    { 
     width: 480px; 
     margin: 1em; 
    } 

    .t-edit-form-container .editor-label, 
    .t-edit-form-container .editor-field 
    { 
     padding-bottom: 1em; 
     float: left; 
    } 

    .t-edit-form-container .editor-label 
    { 
     width: 25%; 
     text-align: right; 
     padding-right: 3%; 
     clear: left; 
    } 
    .t-edit-form-container .editor-field textarea 
    { 
    font-size:11px; 
    width:80%; 
} 
    .t-edit-form-container .editor-field 
    { 
     width: 70%; 
    } 
</style> 
} 
+0

prova a mettere un 'debugger;' nella tua istruzione if che ottiene e.name == "aggiorna" e controlla se arriva al debugger o no –

+0

yap ho già fatto that.it sta arrivando ma alert ('') ; valore è nullo Come sto facendo AJAX chiamata al server. Diventa caldamente in Tempdata ma non è un valore rinfrescante di Javascript –

risposta

13

So che la sua una vecchia questione, ma ho pensato di rispondere mentre stavo cercando per la stessa identica soluzione e speriamo che possa aiutare alcuni altri.

Questo risolto per me how-to-get-the-tempdata-in-javascript

parentesi In sostanza, la sintassi manca

//Your code 
alert('@TempData["AlertMessage"]'); 

// Correct code 
alert('@(TempData["AlertMessage"])'); 

La staffa dopo la @

Spero che questo aiuti la prossima ricercatore come me.

2

TempData utilizzare quando reindirizzare all'azione. Prova ViewBag.

In regolatore:

ViewBag.AlertMessage = status.Message; 

In considerazione:

@{ 
    ViewBag.Title = "Operation List"; 
    string alert = "Your custom error message"; 

    if(ViewBag.AlertMessage != null) 
    { 
     alert = (string)ViewBag.AlertMessage; 
    }   
} 

e javascript

var jsAlert = '@alert'; 
alert(jsAlert); 
+0

La tua risposta sembra essere intelligente, ma ricevo un errore "Il nome 'avviso' non esiste nel contesto attuale". D'altra parte, con Html.BeginForm potrei passare i messaggi da Controller a View usando TempData o ViewBag. Ma con l'Ajax, non posso passare. Quindi, la tua risposta risolve questo problema? O quali modifiche dovrebbero essere applicate? Grazie in anticipo. –

+0

si ottiene questo errore ("Il nome 'avviso' non esiste nel contesto corrente") perché la variabile 'alert' dovrebbe trovarsi nella stessa pagina con il codice js e top of view. Secondo, vuoi passare i dati dal controller alla vista o dalla vista al controller con ajax? Non riesco a ottenere domande bene. –

+0

Voglio passare i dati da Controller a View. D'altra parte, sarebbe meglio digitare le variabili necessarie nella risposta in modo che le altre persone che non hanno esperienza sufficiente possano usarle facilmente. Grazie. –