Is there an easy way to caputer the output of a view or partial view as a string?
Asked
Active
Viewed 1,223 times
1 Answers
3
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

jim tollan
- 22,305
- 4
- 49
- 63
-
2This solution works for partials that don't have refenece to "Request" field inside the ascx file. If they have - the "Request is not available in this context" exception is thrown. Workaround for that would be to change "Request" references to "HttpContext.Current.Request". I'm still looking for some easier and less messy way of rendering partial view to string in MVC2 – PanJanek May 13 '10 at 08:18