如何呈现在控制器局部视图对JSON视图、控制器、局部、呈现在

2023-09-04 01:15:28 作者:上邪

我不知道我怎么能呈现局部视图中使用的JsonResult在我的控制器?

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

}

推荐答案

RenderPartialView 是它呈现的视图,作为字符串自定义的扩展方法

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

这是没有提及的在文章中(你所提到最初),但你会发现它贴在本文的示例code。 它可以在\助手\ Reders.cs中找到

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

下面是$ C $的方法有问题的C:

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