Created
April 18, 2013 04:57
-
-
Save aranm/5410239 to your computer and use it in GitHub Desktop.
Render a partial razor view to a string. Can't remember where this code came from originally (it isn't mine)
This file contains hidden or 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 static string RenderPartialViewToString(Controller controller, string pathToView, object viewModel, | |
ViewDataDictionary viewData = null) { | |
String result; | |
var viewEngine = ViewEngines.Engines.FindPartialView(controller.ControllerContext, pathToView); | |
using (var writer = new StringWriter()) { | |
var vd = viewData == null ? new ViewDataDictionary(viewModel) | |
: new ViewDataDictionary(viewData) { Model = viewModel }; | |
var viewContext = new ViewContext(controller.ControllerContext, | |
viewEngine.View, | |
vd, | |
new TempDataDictionary(), writer); | |
viewEngine.View.Render(viewContext, writer); | |
result = writer.ToString(); | |
} | |
return result; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment