Monday, January 26, 2015

Render MVC View as String


Views are essential part of ASP.NET MVC and we can take advantage of Views in situations like where we need email template to be sent on user registration. So here are the steps I have done in order to use a view as email message body.
  1. Styles must be inline in your View.
  2. Render your View by passing Model.
  3. Get HTML (string) result to set it as email body.
Following method will get you output HTML for the view which you can use in your email body.

private string ViewToString(string viewName, object model)
{
    ViewData.Model = model;
    using (var sw = new System.IO.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();
    }
}

0 comments:

Post a Comment

Twitter Delicious Facebook Digg Stumbleupon Favorites More