render view as a string in mvc 2
Is there an easy way to caputer the output of a view or 开发者_Go百科partial view as a string?
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. 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
精彩评论