下面是一些代碼,因爲我需要這個今天這樣做會奏效。 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結果
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);
}
和部分有一個強類型的視圖模型
<%@ Control Language="C#" Inherits="System.Web.Mvc.ViewUserControl<SomeObject>" %>
<h1>My Partial</h1>
聽起來像是他知道如何使用JsonResults,我認爲他試圖將PartialView有JsonResult ... – Alconja 2009-07-23 00:15:14
接下來的問題是措辭相當糟糕結合起來。 – rball 2009-07-23 16:47:36