Continous refresh of PartialView using ASP.NET MVC 3

Casper picture Casper · May 30, 2011 · Viewed 15.9k times · Source

I am developing a website using ASP.NET MVC 3.

I have a number of sections containing news from different departments, as shown in the picture below:

http://i.stack.imgur.com/G21qi.png

The sections are added to the masterpage by using

@Html.Action("_News", "Home", new { id = 1 })

Where id 1 = "Ledelsen", 2 = "Omstillingen" and so on.

My Controller contains the following Action:

[ChildActionOnly]
public ActionResult _News(int id)
{
    // controller logic to fetch correct data from database
    return PartialView();
}

I got CRUD up and running, but my question is how I can refresh the PartialViews without postback, at a set interval?

I'm guessing I have to use Javascript/jQuery to accomplish this, but I have not been able to.

Can anyone point me in the right direction or better yet, provide an example of how to do this?

Thanks in advance

EDIT: Just to clarify I do not want the whole page to refresh, but only do an asynchronous refresh of the partialviews

Answer

Steve Mallory picture Steve Mallory · May 30, 2011

In your partial view, I'd suggest wrapping the whole thing in a div:

<div id="partial1">

In javascript you'll need a function to use AJAX to load the partial view into the div:

$("#partial1").load("_News", { id="1"} );

That's using jQuery. Some documentation here. Basically, that will replace the div indicated with view generated from the call to your _News action. The id can be varied if you add some logic to the javascript call.

Then wrap the call to load() in a setTimeout():

var t = setTimeout(function () {$("#partial1").load("_News", { id="1"} );}, 60000);

That will run the included function every 60 seconds. t can be used, thusly clearTimeout(t) anywhere in your javascript code to stop the auto refreshing.

EDIT

This should address the caching issue. Thanks @iko for the suggestion. I've noticed you need cache: false for this to work.

var t = setTimeout(function () { $.ajax({ 
                                     url: "_News", 
                                     data: { "id": "1" }, 
                                     type: "POST", 
                                     cache: false, 
                                     success: function (data) { 
                                          $("#partial1").innerHTML = data; 
                                     }}); }, 60000);