1

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

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

因为我想使用 Ajax 进行更改(每 10 秒,我调用 Ajax)

请看下面的代码,

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

 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天才请!!!如果不可能,有什么想法吗?

4

1 回答 1

2

ViewData/ ViewBag(这是一个包装器ViewData)用于将控制器之间的数据传递给视图,并且无论是 AJAX 还是普通请求,它们都会在每个请求中重新创建。他们不能帮助你保持状态:(

于 2012-10-27T03:39:22.367 回答