Skip to content

Instantly share code, notes, and snippets.

@aranm
Created April 18, 2013 04:57
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save aranm/5410239 to your computer and use it in GitHub Desktop.
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)
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