setInterval()

Published 1/14/2012 by James in ASP.NET MVC | jQuery

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.


$.ajax() statusCode setting

Published 9/7/2011 by James

I learned something really interesting today. The jQuery ajax function has a statusCode setting that allows you to respond to HTTP status codes differently.

$.ajax({
    url: 'Default.aspx/GetDater',
    type: 'POST',
    contentType: 'application/json',
    dataType: 'json',
    error: function(jqXHR, textStatus, errorThrown) { alert('error'); },
    statusCode: {
        200: function() { alert('a 200 occurred'); },
        500: function() { alert('a 500 occurred'); },
        409: function(jqXHR, textStatus, errorThrown) {
            if (errorThrown == 'Conflict') {
                alert('user exists');
            }
        }
    }
});

In this function I am wiring handlers to respond to status codes, 200, 500, and 409. Something else worth mentioning here is if you declare a success and/or error method in this ajax call, it will fire prior to the statusCode handler. You can learn more about this setting and other ajax settings here.

James


.NET Fanatic

fa·nat·ic /fəˈnatik/
Noun: A person marked or motivated by an extreme, unreasoning enthusiasm, as for a cause or software development...specifically .NET.