在ASP.NET MVC中的JSON属性中返回呈现的HTML部分

Lan*_*her 4 asp.net-mvc json

我很高兴从ASP.NET中的控制器返回JsonResult对象或部分ASP.NET视图.

我想将渲染的局部视图作为JSON对象中的属性返回.例如

请求

/post/detail/1
Run Code Online (Sandbox Code Playgroud)

会回来的

{"PostId": 1, "Html": "<p>some markup rendered from a partial to inject</p>" }
Run Code Online (Sandbox Code Playgroud)

当我在JavaScript中处理响应时,这将允许我知道PostId.有关最佳方法的任何提示吗?

sup*_*cal 10

以下是一些可行的代码,因为我今天需要这样做.这里描述了原始代码.

public static string RenderPartialToString(string controlName, object viewData)
{
    var viewContext = new ViewContext();
    var urlHelper = new UrlHelper(viewContext.RequestContext);
    var viewDataDictionary = new ViewDataDictionary(viewData);

    var viewPage = new ViewPage
    {
        ViewData = viewDataDictionary,
        ViewContext = viewContext,
        Url = urlHelper
    };

    var control = viewPage.LoadControl(controlName);
    viewPage.Controls.Add(control);

    var sb = new StringBuilder();
    using (var sw = new StringWriter(sb))
    using (var tw = new HtmlTextWriter(sw))
    {
            viewPage.RenderControl(tw);
    }

    return sb.ToString();
}
Run Code Online (Sandbox Code Playgroud)

然后,您可以使用它来执行RJS样式的json结果

public virtual ActionResult Index()
{
    var jsonResult = new JsonResult
    {
        Data = new
        {
            main_content = RenderPartialToString("~/Views/contact/MyPartial.ascx", new SomeObject()),
            secondary_content = RenderPartialToString("~/Views/contact/MyPartial.ascx", new SomeObject()),
        }
    };

    return Json(jsonResult, JsonRequestBehavior.AllowGet);
}
Run Code Online (Sandbox Code Playgroud)

而partial有一个强类型的视图模型

<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeObject>" %>
<h1>My Partial</h1>
Run Code Online (Sandbox Code Playgroud)