Convert PartialView to HTML

DmitryBoyko picture DmitryBoyko · Aug 20, 2013 · Viewed 23.6k times · Source

I am just wondering if it is possible to convert

PartialView("_Product", model)

to html so we can send it back with JSON ?

return Json(result, JsonRequestBehavior.AllowGet);

Answer

Leo Nix picture Leo Nix · Aug 20, 2013

Absolutely, put the following method in a shared controller or a helper class. It will return the rendered view in HTML, the usage is self explainatory:

public static string RenderViewToString(ControllerContext context, string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = context.RouteData.GetRequiredString("action");

    var viewData = new ViewDataDictionary(model);

    using (var sw = new StringWriter())
    {
        var viewResult = ViewEngines.Engines.FindPartialView(context, viewName);
        var viewContext = new ViewContext(context, viewResult.View, viewData, new TempDataDictionary(), sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}