How to render partial view in controller for Json

核能气质少年 提交于 2019-12-04 05:40:45

问题


I'm wondering how can I render a partial view to be used in a JsonResult in my controller?

return Json(new
{
    Html = this.RenderPartialView("_EditMovie", updatedMovie),
    Message = message
}, JsonRequestBehavior.AllowGet);

}


回答1:


RenderPartialView is a custom extension method which renders a view as a string.

It wasn't mentioned in the article (what you have referred originally) but you find it in the sample code attached to the article. It can be found under the \Helpers\Reders.cs

Here is code of the method in question:

public static string RenderPartialView(this Controller controller, 
    string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = controller.ControllerContext.RouteData
            .GetRequiredString("action");

    controller.ViewData.Model = model;
    using (var sw = new StringWriter())
    {
        ViewEngineResult viewResult = ViewEngines.Engines
            .FindPartialView(controller.ControllerContext, viewName);
        var viewContext = new ViewContext(controller.ControllerContext, 
            viewResult.View, controller.ViewData, controller.TempData, sw);
        viewResult.View.Render(viewContext, sw);

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


来源:https://stackoverflow.com/questions/11955015/how-to-render-partial-view-in-controller-for-json

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