2

Is it possible to call an action of another controller and receive its resultant view as a string?

I would like to use a standard behaviour of .net mvc which allows me to create e-mail message basing on proper model and view. I know that I can use RazorEngine but in this instance I have to pass a full path to view and I should overwrite base class if I want to use eg. @Html or @Url.

John Saunders
  • 160,644
  • 26
  • 247
  • 397
gis
  • 141
  • 11
  • You would like to call this from a `Controller` or business layer class? You can fairly easily get the full path to a view using [`VirtualPathUtility`](http://msdn.microsoft.com/en-us/library/system.web.virtualpathutility(v=vs.110).aspx) – Rhumborl Jan 02 '15 at 18:36
  • In which context ? The straight-forward way would be to call @Html.Action if you have a HtmlHelper. http://msdn.microsoft.com/en-us/library/system.web.mvc.html.childactionextensions.action.aspx – driis Jan 02 '15 at 18:36
  • 4
    Have you seen [this article](http://www.codemag.com/Article/1312081)? – Leonardo Herrera Jan 02 '15 at 18:37
  • 1
    yes, check [this question](http://stackoverflow.com/questions/483091/render-a-view-as-a-string) – Jonesopolis Jan 02 '15 at 18:39

1 Answers1

0

I've done this in a couple of cases by adding the following to my base controller class.

protected string RenderViewToString(string viewName, object model = null)
{
  ViewData.Model = model;
  using(StringWriter sw = new StringWriter())
  {
    ViewEngineResult viewResult = ViewEngines.Engines.FindView(ControllerContext, viewName, null);
    ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);

    return sw.GetStringBuilder().ToString();
  }
}

protected string RenderPartialViewToString(string viewName, object model = null)
{
  ViewData.Model = model;
  using(StringWriter sw = new StringWriter())
  {
    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
    ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
    viewResult.View.Render(viewContext, sw);

    return sw.GetStringBuilder().ToString();
  }
}
Josh
  • 1,724
  • 13
  • 15