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);
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();
}
}
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
}
})
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With