This is something that I put together in a few minutes to provide a way to refresh a partial view on a specified time interval.
Let’s create a MVC User Control that displays the current date and time called "TimeControl.ascx":
We can render this in a view using the Html.RenderPartial() method. How can we update this control using AJAX? MVC provides an Ajax.ActionLink() helper method that we could use. An example of this can be found here and here. The only problem with this is that you have to click a link to update the control. What if we want it to automatically update the partial view control via AJAX on a certain time interval, like every 5 seconds? To do this, I have created a helper method that provides this functionality.
The code for the helper method (Html.RenderPartialRefresh) is shown below:
The next step is to make sure that we have the AJAX scripts registered. In the master page or the view, ensure that you have the following script references (with the correct path to the scripts):
And now, lets create a controller action method to return the partial view when called. In this example, we will add the action method to the Home controller, and it simply returns a View of the TimeControl.ascx partial view. This is called by the AJAX script every interval to update the partial view.
Finally, to render the auto updating view, we can use the helper method that we created above, passing the name for the wrapping div ("timeDisplay"), the controller and action method to call for the update ("Home" and "GetTimeControl"), the TimeSpan for the interval (5 seconds), and the partial view to render ("TimeControl.ascx"):
Initially, the View will be rendered with the Date and Time of the request as shown below:
And every five seconds, the partial view control will update via AJAX (without a postback) to reflect the current time. The image below shows the same page after 80 seconds without the need for a refresh. You can see that the time has automatically updated.