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?
2 Answers
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();
}
1 Comment
xster
Api.ControllerContext is System.Web.Http.Controllers.HttpControllerContext and FindView needs System.Web.Mvc.ControllerContext...
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.
1 Comment
xster
I believe MVC 4 is not yet supported with Postal