2012-10-27 66 views
1

ViewBag,ViewData,TempData在我第一次調用視圖時被調用一次?ViewBag在ASP.NET MVC3中使用ajax更改

如果我不刷新頁面,永不改變?

因爲我想使用Ajax改變(每10秒,我調用Ajax的)

PLZ見下文代碼,

================= ===在控制器...... =======================

public ActionResult OriginView() 
{ 

     ViewBag.IntData = 1; 

     return View(); 

} 


public JsonResult ChangeViewBag(int CurrentInterval) 
{ 

     ViewBag.IntData = CurrentInterval; 

     return Json(new{IntData=CurrentInterval},JsonRequestBehavior.AllowGet); 

} 

============ =====在OriginView.cshtml中=======================

var CurrentInterval = 2 

$.getJSON('@Url.Action("ChangeViewBag","Controller")', {CurrentInterval:CurrentInterval},function(response){ 

    @*CurrentInterval++ every ten sec, I want to use CHANGED ViewBag here!*@ 

    alert(@ViewBag.IntData) @*but **Result is still 1**, unchanged!*@ 

    alert(response.IntData) @*ofcourse I can use it in this way. *@ 

    @* but I should use below ASP.NET CODE 

    @{ 
     string TimeData = DateTime.Now.AddSeconds(**ViewBag.IntData**).ToString(); 
    } 

    ***The position is impossible to javascript variable.*** right?*@ 
}); 

.Net天才請!!! 如果不可能,任何想法?

+1

該代碼正在做你正在問的事情,也許你可以花更多的時間在關於你想要做什麼的敘述上嗎?你似乎是依靠ViewBag在JavaScript中有很多,這就像是期待美國的一艘戰列艦參與我在堪薩斯州生產的一種花生醬三明治。 – jcolebrand

+0

知道了!欣賞我吸引力! – user1645680

+0

然而,你沒有給出敘述,我很困惑。 – jcolebrand

回答

2

ViewData/ViewBag(這是周圍ViewData一個包裝)用於控制器之間傳遞數據的圖和它們在每個請求中它是否是AJAX或正常重新創建。他們不幫你保持狀態:(