如何在2个或更多JSON字段中返回HTML?
return Json(
new
{
Breadcrumbs = PartialView("Breadcrumbs/Breadcrumbs", model.Breadcrumbs),
FolderDetail = PartialView("Detail/Folder", model.FolderDetail)
});
在这种情况下,我不会在result.BreadCrumbs和result.FolderDetail中获取HTML,而是获取JSON对象
答案 0 :(得分:3)
PartialView是一个ActionResult,它告诉系统渲染局部视图而不是输出HTML。这是我目前用于在将字符串添加到JSON结果之前将其呈现给字符串的代码:
public static string RenderPartialToString(this Controller controller, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = controller.ControllerContext.RouteData.GetRequiredString("action");
controller.ViewData.Model = model;
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw);
return sw.GetStringBuilder().ToString();
}
}