[英]render view as a string in mvc 2
有没有一种简便的方法可以将视图或部分视图的输出捕获为字符串?
for a partial view, no problem: 对于局部视图,没问题:
public static class ExtensionMethods
{
public static string RenderPartialToString(this ControllerBase 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();
}
}
usage in controller : 控制器中的用法:
public string GetLocationHighlites()
{
// get the model from the repository etc..
return this.RenderPartialToString("PartialViewName", model);
}
not sure about the usage for a 'normal' view as it wouldn't invoke the vp.LoadControl() part. 不确定“普通”视图的用法,因为它不会调用vp.LoadControl()部分。 however, i'm sure someone will have the similar code required for doing the same thing with a 'normal' view.
但是,我确定有人会以“正常”视图执行相同操作所需的类似代码。
hope this partialview one helps you out for now. 希望这种局部视图现在可以帮助您。
jim 吉姆
There were plenty of questions related to yours. 有很多与您有关的问题。 Notably, Render a view as a string shall fit your requirements.
值得注意的是, 将视图渲染为字符串应符合您的要求。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.