在ASP.NET MVC3中使用ajax更改ViewBag

时间:2012-10-27 02:00:43

标签: ajax asp.net-mvc exchange-server viewbag

ViewBag,ViewData,TempData在我第一次调用视图时只调用一次?

如果我不刷新页面,永远不会改变?

因为我想使用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 个答案:

答案 0 :(得分:2)

ViewData / ViewBag(这是ViewData的包装)用于在控制器之间传递数据到视图,在每个请求中重新创建它们这是AJAX还是正常。它们无法帮助您维持状态 :(