I read an interesting article today around periodically updating data in an MVC view on set intervals. It was rather simple and uses a setInterval() javascript method.
First we setup a method, GetDateTime(), that returns a PartialViewResult that I will call via a GET request. I then setup the initial controller action, Index(), and reuse the GetDateTime() method to bind the DateTime to the ViewBag.
public ActionResult Index()
{
ViewBag.DateTime = GetDateTime().ViewBag.DateTime;
return View();
}
public PartialViewResult GetDateTime()
{
ViewBag.DateTime = DateTime.Now;
return PartialView( "Time" );
}
My PartialView, named Time, looks a little like this:
<span id="time">@ViewBag.DateTime</span>
And the Index View looks like this:
<div id="content">@{ Html.RenderPartial( "Time", ( object ) ViewBag.DateTime ); }</div>
Now if you run this as is, the page should render the current time, without a refresh. Now let's wire the Index view with a little javascript to refresh in intervals.
<script type="text/javascript">
$(function () {
setInterval(function () {
$('#content').load('Home/GetDateTime');
}, 1000);
});
</script>
This setInterval function basically takes two parameters, in this example. The first is the code to execute, and the second parameter is the interval, in milliseconds. Here, our first parameter uses the jquery load method to make a GET request to the specified URL, every second. The result returned is assigned to the DOM element that matches the jQuery selector, the <div> with the id of 'content'. For more on the setInterval method, click here.
This is an extremely simplistic example, and considerations should be thought out prior to implementing this type of polling. I would imagine in a heavy traffic environment that given the interval and the data returned, this could get expensive.