14

I would like to use my Razor view as some kind of template for sending emails, so I would like to "save" my template in a view, read it into controller as a string, do some necessary replacements, and then send it.

I have solution that works: my template is hosted somewhere as an HTML page, but I would like to put it into my application (i.e. in my view). I don't know how to read a view as a string in my controller.

alex
  • 6,818
  • 9
  • 52
  • 103
Vlado Pandžić
  • 4,879
  • 8
  • 44
  • 75

2 Answers2

20

I use the following. Put it on your base controller if you have one, that way you can access it in all controllers.

public static string RenderPartialToString(Controller controller, string viewName, object model)
{
    controller.ViewData.Model = model;

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

        return sw.GetStringBuilder().ToString();
    }
}
Mathew Thompson
  • 55,877
  • 15
  • 127
  • 148
7

Take a look at the RazorEngine library, which does exactly what you want. I've used it before for email templates, and it works great.

You can just do something like this:

// Read in your template from anywhere (database, file system, etc.)
var bodyTemplate = GetEmailBodyTemplate();

// Substitute variables using Razor
var model = new { Name = "John Doe", OtherVar = "Hello!" };
var emailBody = Razor.Parse(bodytemplate, model);

// Send email
SendEmail(address, emailBody);
Garrett Vlieger
  • 9,354
  • 4
  • 32
  • 44
  • This is useful, but I have some code already written which I don't want to change. I would like only to save my template(html) in view, and literally read html from view as string, and do replacements in controller. – Vlado Pandžić Mar 12 '13 at 20:56
  • Understood. I've done what you're doing in the past. However, once I discovered the RazorEngine library, I've found it not only makes developing template parsing a lot easier, but it makes it much simpler to maintain your templates. You can store the templates in a database or somewhere that you can edit them without editing code. – Garrett Vlieger Mar 12 '13 at 21:00
  • Is it possible to do something similar by using the `Microsoft.AspNet.Razor`? Just looking to solve the problem within Microsoft so that I don't have to justify another depdendency. – Coder Absolute Oct 25 '18 at 12:43