Mr. Zen
Mr. Zen

Reputation: 712

Periodically Refresh a partial view ( ASP.Net MVC)

I need a periodic refresh of .Net's partial view. It is working with Ajax.ActionLink, is there a similar feature for periodic refresh? Can I do it without using jQuery?

Upvotes: 8

Views: 10310

Answers (3)

Rashad Valliyengal
Rashad Valliyengal

Reputation: 3162

Try this.

 $(document).ready(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        setInterval(function () {
            var url = "@(Html.Raw(Url.Action("ActionName", "ControllerName")))";
            $("#PartialViewDivId").load(url);
        }, 30000); //Refreshes every 30 seconds

        $.ajaxSetup({ cache: false });  //Turn off caching
    });

It makes an initial call to load the div, and then subsequent calls are on a 30 second interval.

In the controller section you can update the object and pass the object to the partial view.

public class ControllerName: Controller
{
    public ActionResult ActionName()
    {
        .
        .   // code for update object
        .
        return PartialView("PartialViewName", updatedObject);
    }
}

Upvotes: 0

Felipe Oriani
Felipe Oriani

Reputation: 38598

Zen, you could do it by a code like this:

function loadPartialView() {
   $.ajax({
    url: "@Url.Action("ActionName", "ControllerName")",
    type: 'GET', // <-- make a async request by GET
    dataType: 'html', // <-- to expect an html response
    success: function(result) {
                $('#YourDiv').html(result);
             }
   });
}

$(function() {

   loadPartialView(); // first time

   // re-call the function each 5 seconds
   window.setInterval("loadPartialView()", 5000);

});

Remember your Action should return a PartialView. I hope it helps you!

Upvotes: 12

Precious Roy
Precious Roy

Reputation: 1086

Maybe this can help you. Which version of MVC are you using? You can set a specified time interval for a helper method. This is the only way I've seen without using js.

Upvotes: 2

Related Questions