Sunday, December 19, 2010

Render ASP.MVC Partial Views (*.ascx) to a String

It seems like every ASP.Net MVC project I work on requires me to do this, so I thought I would post it.

A particularly useful application of this technique is passing HTML from the server to the browser using JSON requests (AJAX).

Here is the code:



public static string RenderPartialToString(string partialViewPath, ViewDataDictionary viewData, ViewContext viewContext)

{

    ViewPage vp = new ViewPage();

    vp.ViewData = viewData;

    vp.ViewContext = viewContext;

    Control control = vp.LoadControl(partialViewPath);

    vp.Controls.Add(control);

    StringBuilder sb = new StringBuilder();

    using (StringWriter sw = new StringWriter(sb))

    {

        using (HtmlTextWriter tw = new HtmlTextWriter(sw))

        {

            vp.RenderControl(tw);

        }

    }

    return sb.ToString();

}




The usage is as follows:
public JsonResult RenderVacationList(int id)
        {
ViewData.Model = //Some model object from your data store
string v = Helper.RenderPartialToString("/Views/ControllerName/PartialViewToRender.ascx", ViewData, new ViewContext());
            return new JsonResult()
            {
                Data = new {
                    view = v
                }
                
            };
        }
You can then call this Action method from your javascript and insert the resulting HTML into the page on the fly! Pretty slick..

As always, leave helpful comments/questions below, Thanks!

No comments:

Post a Comment