Auto Refresh a Partial View of a Page in MVC

I have a partial view in my application home page which displays list of rows from the database table, the data in the table gets updated every two minutes and my requirement is to display the up to date table data. I am going to achieve this with the help of jQuery SetInterval function.

The following image represents partial view which displays list of rows.


Step 1: Place partial view in a DIV.

  1. <Div id=”_recentfive”>  
  2.    @HTML.Partial(“_recent” , ModelObject)  
  3. </Div>  
Step 2: Add jQuery references.

Add the script references in the Header section of _Layout.cshtml.
  1. <script src="~/Scripts/jquery-1.10.2.min.js"></script>  
Step 3: Add script coding to implement setInterval() function.
  1. <script type=”text/javascript”>  
  2.    setInterval(“$(‘#_recentfive’).load(‘controllername/actionmethod’)”,2000);  
  3. </script>  
In the above setInterval Function:
  • recentfive: It is the id of DIV element where partial view is placed.

  • And in the load method, mention controller name and action method which returns the model object to render in the partial view.

  • 2000: It is the duration in millisecons.
Step 4: Modify the action method in your Controller like the following:
  1. [OutputCache(NoStore=true,Location=System.Web.UI.OutputCacheLocation.Client,Duration=2)]  
  2. Public ActionResult Youractionmethod()  
  3. {  
  4.    . . .   
  5.    Return PartialView(“__recent”, ModelObject)  
  6. }  
Note: Make sure the duration property in the attribute above the action method is same as mentioned in the setInterval function.