0

Is there an easy way to caputer the output of a view or partial view as a string?

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

1 Comment

This 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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.