Reputation: 11
ViewBag, ViewData, TempData are called just once at the first time when I call the view?
And never change if I don't refresh the page?
Because I want to change using Ajax (every 10 sec, I call Ajax)
Plz See below code,
==================== in Controller... =======================
public ActionResult OriginView()
{
ViewBag.IntData = 1;
return View();
}
public JsonResult ChangeViewBag(int CurrentInterval)
{
ViewBag.IntData = CurrentInterval;
return Json(new{IntData=CurrentInterval},JsonRequestBehavior.AllowGet);
}
================= in 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 genius please!!! If it's impossible, Any Idea?
Upvotes: 1
Views: 4386
Reputation: 32758
ViewData
/ ViewBag
(this is a wrapper around ViewData
) are used to pass data between a controller to a view and they are re-created in every request whether it's AJAX or normal. They don't help you to maintain state :(
Upvotes: 2