简体   繁体   中英

How to render partial view in controller for Json

How can I render a partial view to be used in a JsonResult in a controller?

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM