16

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);
MysticMagicϡ
  • 28,593
  • 16
  • 73
  • 124
NoWar
  • 36,338
  • 80
  • 323
  • 498

2 Answers2

35

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();
    }
}
Uwe Keim
  • 39,551
  • 56
  • 175
  • 291
Leo Nix
  • 2,085
  • 2
  • 24
  • 37
  • 1
    U are awesome genius man! :) – NoWar Aug 20 '13 at 19:37
  • @Leo Nix How should I create the context argument? I tried to initialize an instance but I don't know the ControllerBase argument of its constructor. – Hosein Feb 07 '16 at 14:44
  • you don't need to create one if you use it in the context a controller action: ControllerContext is a property of the controller so just pass it in. https://goo.gl/pp5AkR – Leo Nix Feb 07 '16 at 23:19
  • Say you're trying to render a partial view in HTML rather than calling it from the controller. Then what do you use as the context? e.g. ` – Levi Fuller Jul 14 '16 at 22:34
  • Thanks mate, you saved my day :) – Mehmet Taha Meral Feb 06 '17 at 00:53
11

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
        }
})
AStopher
  • 4,207
  • 11
  • 50
  • 75
Hager Aly
  • 1,113
  • 9
  • 25