返回一个HTML呈现在JSON属性在ASP.NET MVC部分 [英] Returning a rendered HTML partial in a JSON Property in ASP.NET MVC
问题描述
我一直快乐地返回在ASP.NET从我的控制器JsonResult对象或部分ASP.NET意见。
I've been happily returning JsonResult objects or partial ASP.NET views from my controllers in ASP.NET.
我想返回呈现局部视图作为一个JSON对象的属性。例如。
I would like to return a rendered partial view as a property in a JSON object. e.g.
请求
/post/detail/1
将返回
{"PostId": 1, "Html": "<p>some markup rendered from a partial to inject</p>" }
这将让我知道,当我处理JavaScript中的回应帖子ID。的最佳方式任何提示,做到这一点?
This would allow me to know the PostId when I am handling the response in JavaScript. Any tips on the best way to do this?
推荐答案
下面是一些code,因为我需要这个今天做,将工作。 原来的code为这里描述。
Here is some code that will work cause I needed to do this today. The original code is described here.
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();
}
您就可以用它来做RJS风格JSON结果
You can then use it to do RJS style json results
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);
}
和部分有一个强类型的视图模型
And the partial has a strongly typed view model
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeObject>" %>
<h1>My Partial</h1>
这篇关于返回一个HTML呈现在JSON属性在ASP.NET MVC部分的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!