Convert PartialView to HTML [duplicate]

a 夏天 提交于 2019-12-03 05:59:13

问题


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);

回答1:


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();
    }
}



回答2:


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
        }
})


来源:https://stackoverflow.com/questions/18343378/convert-partialview-to-html

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!