2013-03-25 72 views
5

我想訪問Javascript中的TempData。但獲得空值。 我正在ajax調用更新記錄,我想顯示記錄更新成功的消息。它將來自控制器的UpdateOperation動作。 但目前它會顯示空值。我還使用Firebug檢查它顯示如下:在javascript中訪問tempdata在mvc4

function onComplete(e) { 

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

alert(''); 

} 

這裏是我的控制器

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); 
      } 
     } 
    } 

的代碼在使用時重定向到行動我認爲

@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

嘗試在您的if語句中放置一個'debugger;'獲取e.name ==「update」並檢查它是否與調試器相關 – 2013-03-25 05:26:52

+0

yap我已經完成了這個任務。 ;值爲空因爲我正在對服務器進行AJAX調用。它在Tempdata中獲得calue,但它不是刷新Javascript的價值 – 2013-03-25 05:47:10

回答

13

我知道它的一個老問題,但我想我會回答,因爲我一直在尋找爲完全相同的解決方案,並希望幫助其他人。

這解決了這個問題對我來說how-to-get-the-tempdata-in-javascript

從本質上講,你的語法缺少括號

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

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

支架的@

希望這有助於接下來的搜索像我之後。

2

TempData。嘗試ViewBag

在控制器:

ViewBag.AlertMessage = status.Message; 

鑑於:

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

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

和JavaScript

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

你的答案似乎很聰明,但我得到一個錯誤「名稱'警報'在當前上下文中不存在」。另一方面,使用Html.BeginForm,我可以使用TempData或ViewBag將消息從Controller傳遞到View。但對於Ajax,我無法通過。那麼,你的答案解決了這個問題?或者應該應用哪些更改?提前致謝。 – 2015-06-20 23:23:58

+0

你得到這個錯誤(「名稱'警報'在當前上下文中不存在」),因爲'alert'變量應該與js代碼和頂部視圖位於同一頁面中。其次,你想通過ajax從控制器傳遞數據到視圖還是從視圖到控制器?我不能很好地解決問題。 – 2015-06-21 14:36:32

+0

我想將Controller中的數據傳遞給View。另一方面,最好在答案中輸入必要的變量,以便其他沒有足夠經驗的人可以輕鬆使用它們。謝謝。 – 2015-06-21 16:25:51