Rendering a View to a String – Email Templates in MVC4

Hey everyone,

This is just a short post showing how to render views as strings. I’ve used this as a quick way to generate email templates. The logic to render a view as a string is as follows:

public static string RenderRazorViewToString(Controller controller, string viewName, string content)
            controller.ViewBag.Content = content;

            using (var sw = new StringWriter())
                var viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
                var viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
                viewResult.View.Render(viewContext, sw);
                viewResult.ViewEngine.ReleaseView(controller.ControllerContext, viewResult.View);

                return sw.GetStringBuilder().ToString();

The Email Template: Views/Emails/DefaultTemplate

    Layout = null;


    Easy Carts


In your controller:

public String TestEmail(String content)
            Email email = new Email() {
                To = "",
                From = Email.Fields.From.NoReply,
                Body = content,
                Subject = "Test",
                TemplateName = @"~ViewsEmailsDefaultTemplate.cshtml",
                UseTemplate = true

            return email.Body.ToString();

If you looking to implement this with your emails, note that it builds on top of the email class we created back in this post:

If you’re just going to be using it directly within the controller, using the original code from over StackOverflow will probably be your best bet:



, ,



3 responses to “Rendering a View to a String – Email Templates in MVC4”

  1. FOJ Avatar

    Can i please get the implemented email from you as i av been struggling and i’ve not been able to implement it


    1. Chris Owens Avatar
      Chris Owens

      Hey FOJ,

      Sorry I don’t have the code available anymore – what issues are you getting?



  2. FOJ Avatar

    I dont know where to put the RenderRazorViewToString class exactly and how to set up the templatename


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

Create a website or blog at

%d bloggers like this: