如何呈现在控制器局部视图对JSON [英] How to render partial view in controller for Json

查看:83
本文介绍了如何呈现在控制器局部视图对JSON的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道我怎么能呈现局部视图中使用的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();
    }
}

这篇关于如何呈现在控制器局部视图对JSON的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆