I’m using Ajax to refresh a partial view and find that the ViewBag contents are not available when the controller is invoked to perform the refresh.
Specifically, I place an item in ViewBag.ItemToMonitor. It is available the first time the partial view is rendered (here I use it in the controller, but I also tried using it in the view). When the partial view is refreshed via Ajax, the ViewBag does not contain anything for ItemToMonitor.
How can I make data available upon refresh?
Here’s a simple example, based on the MVC 3 project template:
Index.cshtml
<div>
Select an item to monitor:
<ul>
<li>@Html.ActionLink("One", "Monitor", new { itemToMonitor = "Item One" })</li>
<li>@Html.ActionLink("Two", "Monitor", new { itemToMonitor = "Item Two" })</li>
<li>@Html.ActionLink("Three", "Monitor", new { itemToMonitoritem = "Item Three" })</li>
</ul>
</div>
Monitor.cshtml
@model string
<script type="text/javascript">
setInterval(function () {
$.post('@Url.Action("_MonitorDetails")', function (data) {
$('#refreshMe').html(data);
}
);
}, 5000);
</script>
<h2>Monitor</h2>
<div>Monitoring @ViewBag.ItemToMonitor</div>
<div id="refreshMe">
@Html.Partial("_MonitorDetails")
</div>
_MonitorDetails.cshtml
@model string
<div style="background-color:Blue; color:White">
This is my partial view to monitor '@Model', updated at @DateTime.Now.ToString("u").
</div>
HomeController.cs
public ActionResult Index()
{
ViewBag.Message = "Welcome to ASP.NET MVC!";
return View();
}
public ActionResult Monitor(string itemToMonitor)
{
ViewBag.ItemToMonitor = itemToMonitor;
return View((object)itemToMonitor);
}
public ActionResult _MonitorDetails()
{
string itemToMonitor = ViewBag.ItemToMonitor;
// itemToMonitor is null. Why?
return PartialView((object)itemToMonitor);
}
Don’t think a ViewBag in MVC is like a ViewState in WebForms – it is NOT refilled at every request like the ViewState. You have to set everything in the ViewBag again on the next request.
So you need another solution, either