0
有没有简单的方法将视图或局部视图的输出用作字符串?将视图呈现为mvc中的字符串2
有没有简单的方法将视图或局部视图的输出用作字符串?将视图呈现为mvc中的字符串2
为局部视图,没问题:
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();
}
}
用法在控制器:
public string GetLocationHighlites()
{
// get the model from the repository etc..
return this.RenderPartialToString("PartialViewName", model);
}
不能确定的使用情况“正常”视图,因为它不会调用VP。 LoadControl()部分。然而,我相信有人会用'正常'的观点来做同样的事情。
希望这个部分视图帮助你现在。
吉姆
有很多与你有关的问题。值得注意的是,Render a view as a string应符合您的要求。
此解决方案适用于没有参考ascx文件内的“请求”字段的部分。如果他们有 - “请求在此上下文中不可用”异常被抛出。解决方法是将“请求”引用更改为“HttpContext.Current.Request”。我仍然在寻找一些更简单,更麻烦的方法来将部分视图渲染为MVC2中的字符串 – PanJanek 2010-05-13 08:18:18