Thursday, November 13, 2014

Render a mvc view as a string

Here's what I came up with, and it's working for me. I added the following method(s) to my controller base class. (You can always make these static methods somewhere else that accept a controller as a parameter I suppose)
MVC2 .ascx style
protected string RenderViewToString<T>(string viewPath, T model) {
  ViewData.Model = model;
  using (var writer = new StringWriter()) {
    var view = new WebFormView(viewPath);
    var vdd = new ViewDataDictionary<T>(model);
    var viewCxt = new ViewContext(ControllerContext, view, vdd,
                                new TempDataDictionary(), writer);
    viewCxt.View.Render(viewCxt, writer);
    return writer.ToString();
  }
}
Razor .cshtml style
public string RenderRazorViewToString(string viewName, object model)
{
  ViewData.Model = model;
  using (var sw = new StringWriter())
  {
    var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext,
                                                             viewName);
    var viewContext = new ViewContext(ControllerContext, viewResult.View,
                                 ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);
    viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
    return sw.GetStringBuilder().ToString();
  }
}
Edit: added Razor code.
share|improve this answer
12 
Rendering a view to a string is always "inconsistent with the whole routing concept", as it has nothing to do with routing. I'm not sure why an answer that works got a down vote. –  Ben Lesh Nov 3 '10 at 20:15 
3 
I think you might need to remove the "static" from the Razor version's method declaration, otherwise it can't find ControllerContext et al. –  Mike Jan 14 '12 at 5:10
3 
You'll need to implement your own method of removal for those superfluous whitespaces. The best way I can think of off the top of my head is to load the string into an XmlDocument, then write it back out to a string with an XmlWriter, as per the link I left in my last comment. I really hope that helps. –  Ben Lesh Feb 16 '12 at 14:01
2 
Hmm how should I do this using a WebApi Controller, any suggestions would be appreciated –  AlexanderMay 6 '13 at 16:41
2 
Hi everyone to use it with "Static" keyword for all controllers to make it common you have to make static class and inside it you have to put this method with "this" as parameter to "ControllerContext" . You can see here stackoverflow.com/a/18978036/2318354 it . –  Dilip0165 Sep 24 '13 at 9:49