Partial View Auto Refresh in ASP.NET MVC3

| Comments

Problem

A partial view in ASP.NET MVC3 needs to be refreshed on every particular interval.

Let us take a typical ASP.NET MVC3 application. In the HomeController, there is a action called “Quote” which displays funny software quote for every new request like below:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public class HomeController : Controller
{
  public static string[] quotes = {
      "The first 90% of the code accounts for the first 90% of the development time. The remaining 10% of the code accounts for the other 90% of the development time",
      "In order to understand recursion, one must first understand recursion",
      "I have always wished for my computer to be as easy to use as my telephone; my wish has come true because I can no longer figure out how to use my telephone.",
      "The gap between theory and practice is not as wide in theory as it is in practice.",
      "Nine people can’t make a baby in a month"
  };

  // other actions

  public ActionResult Quote()
  {
      var r = new Random();
      var rv = r.Next(0, 4);
      ViewBag.Quote = quotes[rv];
      return PartialView("_Quote");
  }
}

The partial view “_Quote.cshtml” has nothing other than the code below

1
<h3>@ViewBag.Quote</h3>

This whole thing needs to be refreshed without any user interaction on every 10 seconds

Solution

Use setInterval() at client side and set up OutputCacheAttribute on the respective action. The duration should be same on both side.

In the corresponding script of this view, place the below JavaScript:

1
2
3
// jQuery used

setInterval("$('#quote').load('/home/quote')", 10000); // every 10 sec

In the main view, create a div with id “quote” like:

In the action method set the OutputCacheAttribute like:

1
2
3
4
5
[OutputCache(NoStore=true, Location = OutputCacheLocation.Client, Duration = 10)] // every 10 sec
public ActionResult Quote()
{
...
}