Skip to content

Instantly share code, notes, and snippets.

@brainded
Last active January 4, 2016 03:49
Show Gist options
  • Save brainded/8564071 to your computer and use it in GitHub Desktop.
Save brainded/8564071 to your computer and use it in GitHub Desktop.
Useful snippet that allows you to render a MVC View to a string.
private string RenderViewToString(string viewName, object model)
{
// assign the model of the controller from which this method was called to the instance of the passed controller (a new instance, by the way)
this.ViewData.Model = model;
// initialize a string builder
using (StringWriter sw = new StringWriter())
{
// find and load the view or partial view, pass it through the controller factory
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(this.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(this.ControllerContext, viewResult.View, this.ViewData, this.TempData, sw);
// render it
viewResult.View.Render(viewContext, sw);
// return the razorized view/partial-view as a string
return sw.ToString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment