[英]asp.net mvc 1.0 - how to render a partial view as a string
我需要在控制器動作中為字符串呈現局部視圖。 我有以下示例代碼,但有ControllerContext。 在mvc 1.0中似乎不存在ParentActionViewContext
// Get the IView of the PartialView object.
var view = PartialView("MyPartialView").View;
// Initialize a StringWriter for rendering the output.
var writer = new StringWriter();
// Do the actual rendering.
view.Render(ControllerContext.ParentActionViewContext, writer);
任何提示,不勝感激。
這是實現此目的的一種方法 。 MvcContrib中還有一個BlockRenderer 。
試試這個MVC v1.0(我使用的擴展方法)
public static class Extensionmethods
{
public static string RenderPartialToString(this Controller controller, string partialName)
{
return RenderPartialToString(controller, partialName, new object());
}
public static string RenderPartialToString(this Controller controller, string partialName, object model)
{
var vd = new ViewDataDictionary(controller.ViewData);
var vp = new ViewPage
{
ViewData = vd,
ViewContext = new ViewContext(),
Url = new UrlHelper(controller.ControllerContext.RequestContext)
};
ViewEngineResult result = ViewEngines
.Engines
.FindPartialView(controller.ControllerContext, partialName);
if (result.View == null)
{
throw new InvalidOperationException(
string.Format("The partial view '{0}' could not be found", partialName));
}
var partialPath = ((WebFormView)result.View).ViewPath;
vp.ViewData.Model = model;
Control control = vp.LoadControl(partialPath);
vp.Controls.Add(control);
var sb = new StringBuilder();
using (var sw = new StringWriter(sb))
{
using (var tw = new HtmlTextWriter(sw))
{
vp.RenderControl(tw);
}
}
return sb.ToString();
}
}
用法:
....
string htmlBlock = this.RenderPartialToString("YourPartialView", model);
return htmlBlock;
我在大量的控制器中以100%成功地使用它...
吉姆
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.