Last active
January 4, 2016 03:49
-
-
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.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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