1: public static class RenderExtensions
2: {
3: // Extension method to render a partial view every interval specified.
4: public static void RenderPartialRefresh(this HtmlHelper htmlHelper, string name, string controller, string actionMethod,
5: TimeSpan interval, string partialViewName)
6: {
7: RenderPartialRefresh(htmlHelper, name, controller, actionMethod, interval, partialViewName, htmlHelper.ViewData);
8: }
9:
10: // Extension method to render a partial view every interval specified, and providing a model to the control.
11: public static void RenderPartialRefresh(this HtmlHelper htmlHelper, string name, string controller, string actionMethod,
12: TimeSpan interval, string partialViewName, object model)
13: {
14: if (model == null)
15: throw new ArgumentNullException("model");
16: if (String.IsNullOrEmpty(name))
17: throw new ArgumentException("Argument cannot be null or empty.", "name");
18: if (String.IsNullOrEmpty(partialViewName))
19: throw new ArgumentException("Argument cannot be null or empty.", "partialViewName");
20:
21: // Building the javascript that registers the interval and performs the AJAX request.
22: StringBuilder builder = new StringBuilder();
23: builder.Append("<script language=\"javascript\">");
24: builder.Append("setInterval(function() {");
25: builder.Append("Sys.Mvc.MvcHelpers.$1(");
26: builder.AppendFormat("'{0}',", GenerateUrl(htmlHelper.ViewContext, null, actionMethod, controller, new RouteValueDictionary()));
27: builder.Append("'post','','', { insertionMode: Sys.Mvc.InsertionMode.replace, updateTargetId: '");
28: builder.AppendFormat("{0}", name);
29: builder.Append("'});},");
30: builder.AppendFormat("{0});", interval.TotalMilliseconds);
31: builder.Append("</script>");
32:
33: // Wraps the partial view in a div tag so that we can update by the id of the div.
34: htmlHelper.ViewContext.HttpContext.Response.Output.Write(builder.ToString());
35: htmlHelper.ViewContext.HttpContext.Response.Output.Write("<div id=\"{0}\" name=\"{0}\">", name);
36: htmlHelper.RenderPartial(partialViewName, model);
37: htmlHelper.ViewContext.HttpContext.Response.Output.Write("</div>");
38: }
39:
40: // Method to generate the URL given the controller and action method.
41: private static string GenerateUrl(ViewContext viewContext, string routeName, string actionName,
42: string controllerName, RouteValueDictionary valuesDictionary)
43: {
44: UrlHelper helper = new UrlHelper(viewContext);
45: Type t = typeof(UrlHelper);
46: Object[] paramArray = { routeName, actionName, controllerName, valuesDictionary };
47: MethodInfo m = t.GetMethod("GenerateUrl", BindingFlags.NonPublic | BindingFlags.Instance);
48: string s = (string)m.Invoke(helper, paramArray);
49: return HttpUtility.HtmlAttributeEncode(s);
50: }
51: }