I'm developing an ASP.NET MVC application that will send the user a confirmation email. For the email itself, I'd like to create a view and then render that view and send it using the .NET mail objects.
How can I do this using the MVC framework?
I'm developing an ASP.NET MVC application that will send the user a confirmation email. For the email itself, I'd like to create a view and then render that view and send it using the .NET mail objects.
How can I do this using the MVC framework?
You basically need to use
IView.Render
. You can get the view by usingViewEngineCollection.FindView
(ViewEngines.Engines.FindView
for the defaults). Render the output to aTextWriter
and make sure you callViewEngine.ReleaseView
afterwards. Sample code below (untested):I'll leave viewData / tempData to you.
This worked for me:
As per my comment on Richard's answer, this code did work, but it always resulted in a 'Cannot redirect after HTTP headers have been sent' error.
After a lot of digging around Google and being frustrated, I finally found some code that seems to do the trick, on this article:
http://mikehadlow.blogspot.com/2008/06/mvc-framework-capturing-output-of-view_05.html
This guy's method is to create his own HttpContext.
This method works perfectly (a minor difference is that I had to create a separate Action for rendering my partial view, but no drama there).