Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert PartialView to HTML [duplicate]

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);
like image 985
Friend Avatar asked Aug 20 '13 19:08

Friend


2 Answers

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();
    }
}
like image 93
Leo Nix Avatar answered Nov 17 '22 17:11

Leo Nix


I don't know if it is best practice or not, but if you left it as it is

return PartialView("_Product", model)

Then you can call the method using AJAX:

$.ajax ({
  type: "POST",
        url: _url,
        data: _data,
        success: function (result) {
            // the result is the returned html from the partial view
        }
})
like image 40
Hager Aly Avatar answered Nov 17 '22 15:11

Hager Aly