3

I have an ActionResult in my controller that I want to send an HTML email from, the body of that email is generated by a view. Rather than having 2 actionresults methods in my controller can I just get the result of the view when passed my model and avoid it being sent to the browser?

Slee
  • 27,498
  • 52
  • 145
  • 243
  • possible duplicate of [Render a view as a string](http://stackoverflow.com/questions/483091/render-a-view-as-a-string) – bzlm Mar 03 '11 at 14:20
  • I ended up using this solution: http://persistall.com/archive/2007/12/21/asp.net-mvc---renderview-testing-workaround.aspx – Slee Mar 03 '11 at 14:24

2 Answers2

8

MvcMailer is a brilliant little project that supports generating emails using MVC views. It is available as a NuGet package.

In order to render a view to a string instead of response use this code (relativePath points to your view file):

        var content = string.Empty;
        var view = ViewEngines.Engines.FindView(ControllerContext, relativePath, null);
        using (var writer = new StringWriter())
        {
            var context = new ViewContext(ControllerContext, view.View, ViewData, TempData, writer);
            view.View.Render(context, writer);
            writer.Flush();
            content = writer.ToString();
        }
Jakub Konecki
  • 45,581
  • 7
  • 87
  • 126
  • Api.ControllerContext is System.Web.Http.Controllers.HttpControllerContext and FindView needs System.Web.Mvc.ControllerContext... – xster May 08 '12 at 21:19
4

Take a look at the open source Postal project it's available view NuGet.

Postal lets you create emails using regular MVC views.

Andrew Davey done a presentation on Generating email with View Engines using Postal at mvcConf 2

Or alternatively this blog post shows you a simple way.

David Glenn
  • 24,412
  • 19
  • 74
  • 94