MVC4 auto refresh partial view

* Create new MVC4 application and make sure you configure unobtrusive-ajax as described in How to use MVC3 with AJAX

* Create Controller /Controllers/HomeController.cs

public class HomeController : Controller
{
  public ActionResult Index()
  {
    var model = new ViewModel();
    model.Now = DateTime.Now.ToString();
    return View(model);
  }
 
  public ActionResult Refresh()
  {
    var model = new ViewModel();
    model.Now = DateTime.Now.ToString();
    return PartialView("IndexPartial", model);
  }
}
 
public class ViewModel
{
  public string Now { get; set; }
}

* Create view /Views/Home/Index.cshtml

@using MVCTest.Controllers
@{
  ViewBag.Title = "Index";
}
<h2>Index</h2>
<a id="button" title="Refresh now">Refresh Now</a>
<a id="toggleButton" title="Auto refresh every 5 seconds">Auto Refresh</a>
 
<div id="PartialDiv">
  @Html.Partial("IndexPartial", (ViewModel)Model)  
</div>
 
<script type="text/javascript">
 
  var autoRefresh = false;
  var autoRefreshInterval = 1000 * 5;   //mili seconds (set to 5 seconds)
 
  $(document).ready(function () {
    $('a#button').click(function () {
      $('#PartialDiv').load('@Url.Action("Refresh", "Home")');
    });
 
    $('a#toggleButton').click(function () {
      $('#PartialDiv').load('@Url.Action("Refresh", "Home")');
      $(this).toggleClass("down");
      if ($(this).is('.down')) {
        autoRefresh = true;
      } else {
        autoRefresh = false;
      }
    });
 
    var refresh = function () {
      if (autoRefresh) {
        $('#PartialDiv').load('@Url.Action("Refresh", "Home")');
      }
      setTimeout(refresh, autoRefreshInterval);
    };
 
    refresh();
  });
</script>

* Create partial view /Views/Home/IndexPartial.cshtml

<h2>@Model.Now</h2>

* Add these css classes to your Site.css file

#button {
  cursor: pointer;
  font-weight: bold;
}
 
#toggleButton {
  color: darkred;
  font-weight: bold;
  cursor: pointer;
}
 
#toggleButton.down {
  color: green;
  font-weight: bold;
  cursor: pointer;
}

* The webpage should look like this with manual Refresh Now button and Auto Refresh toggle button

mvc4-autorefresh

Comments

  1. Great Post. I have not been visiting the site recently. Took a visit again and there were some great comments on the site. Excellent post. Keep up the good work.
    Web developer

    ReplyDelete

  2. This is awesome!! really helpful for me. Thanks for sharing with us. Following links also helped me to complete my task.

    http://www.codeproject.com/Articles/313500/Partial-View-Auto-Refresh-in-ASP-NET-MVC3

    http://www.mindstick.com/Articles/74634c5e-1c0b-4cba-b7a9-198a99551fac/?Auto%20Refresh%20Partial%20View%20in%20ASP%20NET%20MVC

    ReplyDelete
  3. Mine did not work. I tried it on two workstation settings. The first click on either button refreshes the time, then it does not do anything with click or wait. Any clue? I feel the jquery here is not right. I am wondering what start the event of auto fresh?. Why it does not work when I click Refresh Now for the second time. The color of the button changes for Auto Fresh. But the time is not refreshed. Please help.

    ReplyDelete
  4. Mine did not work. I tried it on two workstation settings. The first click on either button refreshes the time, then it does not do anything with click or wait. Any clue? I feel the jquery here is not right. I am wondering what start the event of auto fresh?. Why it does not work when I click Refresh Now for the second time. The color of the button changes for Auto Fresh. But the time is not refreshed. Please help.

    ReplyDelete
  5. I figured it out myself: I made a few changes: First, The function definition is changed; Second using setInterval function for periodically execute the function. Third, made sure it is not cashing the webpage:
    function refresh() {
    if (autoRefresh) {
    $('#PartialDiv').load('@Url.Action("Refresh", "TimeNow")');
    }
    // setTimeout(refresh, autoRefreshInterval);
    };

    // alert("Hello, this is my ** Second ** alert.");
    setInterval(function () {
    refresh();
    }, 4000);
    $.ajaxSetup({ cache: false }); //Turn off caching

    ReplyDelete
  6. setInterval() looks good. Just to explain the original code the line on the bottom of the script 'refresh();' will call the function first time and then the function will call itself again 'setTimeout(refresh, autoRefreshInterval);'. From my experience when events don't work in javascript it's probably a typo somewhere. Console view in Chrome browser developer view (F12) is very useful for debugging issues like that.

    ReplyDelete
  7. I can't get it to work with images. I'm downloading image from webcam and i want to update image automatically. I just have inside my partial view.

    any help appreciated :)

    ReplyDelete
  8. I just have img src="~/Content/kamera/webcam.jpg" class="img-thumbnail" width="150" height="113" inside my partial view.

    ReplyDelete
  9. Sondre it's probably to do with image caching, have a look at this solution on stackoverflow
    http://stackoverflow.com/questions/8299225/jquery-ajax-function-problems-whith-image-caching

    ReplyDelete
  10. madeinstein, thank you! :) I just added webcam.jpg?cachebuster=@DateTime.Now.Second

    ReplyDelete
  11. Just add single line in controller:

    Response.AddHeader("Refresh", "Seconds");

    Example:
    Response.AddHeader("Refresh", "5");

    By using above Example the page will redirect automatically for every 5 seconds

    ReplyDelete

Post a Comment

Popular posts from this blog

Parse XML to dynamic object in C#

C# Crop white space from around the image