Solving development problems  |  About this blog

Archive for the ‘context’ tag

ASP .NET MVC: How to render View into a string

Sometimes a developer needs to render a View as string. Practical scenario would be to create an obvious View and send it via e-mail instead displaying it in browser. Here is a simple way to extract content from a rendered View:

Implement RenderViewToString method

public class HomeController : Controller
{
  protected string RenderViewToString(string viewName, object model)
  {
    string result = null;
    var view = ViewEngines.Engines.FindView(this.ControllerContext, viewName, null).View;
    if (view != null)
    {
      var sb = new StringBuilder();
      using (var writer = new StringWriter(sb))
      {
        var viewContext = new ViewContext(this.ControllerContext, view,
              new ViewDataDictionary(model), new TempDataDictionary(), writer);
        view.Render(viewContext, writer);
        writer.Flush();
      }
      result = sb.ToString();
    }
    return result;
  }
}

Call it in your action method

//Somewhere in HomeController...
public ActionResult Index()
{
    //Render a View named 'Email' to string variable named 'content'
    //Second parameter (model) can be null
    string content = RenderViewToString("Email", new EmailModel());

    //Do something with the content, e.g. send it to e-mail

    //This does nothing to do with rendered string
    return View();
}

Written by developer

March 31st, 2010 at 10:38 pm