21

I'd like to make use of the Model Binding / Rendering capabilities of a Razor View to generate the HTML Body Content for an email I'm sending from my ASP.NET MVC Application.

Is there a way to render a view to a string instead of returning it as the ActionResult of a GET request?

To illustrate I'm looking for something that will do the following...

    public ActionResult SendEmail(int id)
    {
        EmailDetailsViewModel emailDetails = EmailDetailsViewModel().CreateEmailDetails(id);

        // THIS IS WHERE I NEED HELP...
        // I want to pass my ViewModel (emailDetails) to my View (EmailBodyRazorView) but instead of Rending that to the Response stream I want to capture the output and pass it to an email client.
        string htmlEmailBody = View("EmailBodyRazorView", emailDetails).ToString();

        // Once I have the htmlEmail body I'm good to go.  I've got a utilityt that will send the email for me.
        MyEmailUtility.SmtpSendEmail("stevejobs@apple.com", "Email Subject", htmlEmailBody);

        // Redirect another Action that will return a page to the user confirming the email was sent.
        return RedirectToAction("ConfirmationEmailWasSent");
    }
Justin
  • 10,667
  • 15
  • 58
  • 79
  • 1
    possible duplicate of [how to render a razor view, get the html of a rendered view inside an action](http://stackoverflow.com/questions/4692131/how-to-render-a-razor-view-get-the-html-of-a-rendered-view-inside-an-action) – marcind Mar 10 '11 at 22:19
  • @marcind you are correct. thanks. is there a way for me to mark this as a duplicate? – Justin Mar 11 '11 at 07:09
  • great question! – toddmo Jan 09 '17 at 19:39

7 Answers7

28

If you just need to render the view into a string try something like this:

public string ToHtml(string viewToRender, ViewDataDictionary viewData, ControllerContext controllerContext)
{
    var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null);

    StringWriter output;
    using (output = new StringWriter())
    {
        var viewContext = new ViewContext(controllerContext, result.View, viewData, controllerContext.Controller.TempData, output);
        result.View.Render(viewContext, output);
        result.ViewEngine.ReleaseView(controllerContext, result.View);
    }

    return output.ToString();
}

You'll need to pass in the name of the view and the ViewData and ControllerContext from your controller action.

Ryan Tofteland
  • 913
  • 6
  • 11
  • Very similiar to this solution http://stackoverflow.com/questions/4692131/how-to-render-a-razor-view-get-the-html-of-a-rendered-view-inside-an-action as mentioned by @marcind. But I'll give you the answer since I don't know how to mark this as a duplicate:) Thanks this is the general approach I ended up using. – Justin Mar 11 '11 at 07:17
  • 1
    Thx - looking back I see that I'm missing a using() block on the IDisposable StringWriter. Hopefully you remember that on your end. – Ryan Tofteland Mar 11 '11 at 15:29
  • Hello, I am getting following exception with this code. [InvalidOperationException: The RouteData must contain an item named 'controller' with a non-empty string value.] System.Web.Routing.RouteData.GetRequiredString(String valueName) +3193976 System.Web.Mvc.VirtualPathProviderViewEngine.FindView(ControllerContext controllerContext, String viewName, String masterName, Boolean useCache) +77 – lsc Feb 27 '16 at 10:30
  • Can you add a code snippet to call from a typical controller action? Then your answer will be the best one in S/O history ever. I promise :) – toddmo Jan 09 '17 at 19:43
10

You may checkout Postal for using views for sending emails.

Darin Dimitrov
  • 1,023,142
  • 271
  • 3,287
  • 2,928
  • A neat project gave you a point but I've already got the email sending part all hooked up to my backend so the simple View.Render solution is a fair bit more lightweight for my purposes. Thanks though! – Justin Mar 11 '11 at 07:15
4

Try MvcMailer: http://www.codeproject.com/KB/aspnet/MvcMailerNuGet.aspx

CD..
  • 72,281
  • 25
  • 154
  • 163
3

Another one would be ActionMailer.Net: https://bitbucket.org/swaj/actionmailer.net/wiki/Home

From the website: An MVC 3-based port of the Rails ActionMailer library to ASP.NET MVC. The goal is to make it easy and relatively painless to send email from your application.

NuGet: Install-Package ActionMailer

davehauser
  • 5,844
  • 4
  • 30
  • 45
1

There is also Essential Mail: Razor package from NuGet. It is build over RazorEngine and provides simple interface for email rendering.

Email message template looks something like

@inherits Essential.Templating.Razor.Email.EmailTemplate
@using System.Net;
@{
    From = new MailAddress("example@email.com");
    Subject = "Email Subject";
}
@section Html 
{
   <html>
      <head>
          <title>Example</title>
      </head>
      <body>
          <h1>HTML part of the email</h1>
      </body>
   </html>
}
@section Text 
{
    Text part of the email.
}

The project is hosted on GitHub: https://github.com/smolyakoff/essential-templating/wiki/Email-Template-with-Razor

0

Based on Ryan's answer, I did an extension method:

public static string RenderViewToString(this Controller source, string viewName)
{
  var viewEngineResult = ViewEngines.Engines.FindView(source.ControllerContext, viewName, null);
  using (StringWriter output = new StringWriter())
  {
    viewEngineResult.View.Render(new ViewContext(source.ControllerContext, viewEngineResult.View, source.ViewData, source.TempData, output), output);
    viewEngineResult.ViewEngine.ReleaseView(source.ControllerContext, viewEngineResult.View);
    return output.ToString();
  }
}

To call from inside a controller action (example usage):

  [AllowAnonymous]
  public class ErrorController : Controller
  {
    // GET: Error
    public ActionResult Index(System.Net.HttpStatusCode id)
    {
      Exception ex = null; // how do i get the exception that was thrown?
      if (!Debugger.IsAttached)
        Code.Email.Send(ConfigurationManager.AppSettings["BugReportEmailAddress"], 
          $"Bug Report: AgentPortal: {ex?.Message}", 
          this.RenderViewToString("BugReport"));
      Response.StatusCode = (int)id;
      return View();
    }
  }
toddmo
  • 20,682
  • 14
  • 97
  • 107
0

Still working outside a web app with the last MVC FullFW

http://fabiomaulo.blogspot.com/2011/08/parse-string-as-razor-template.html

You can create a worker consuming queue rendering and sending emails outside the web. Few code lines, you don't need another package over Razor.

Fabio Maulo
  • 427
  • 4
  • 3