Rendering a view on-the-fly

asp.net-mvcframeworksrenderview

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?

Best Answer

You basically need to use IView.Render. You can get the view by using ViewEngineCollection.FindView (ViewEngines.Engines.FindView for the defaults). Render the output to a TextWriter and make sure you call ViewEngine.ReleaseView afterwards. Sample code below (untested):

StringWriter output = new StringWriter();

string viewName = "Email";
string masterName = "";

ViewEngineResult result = ViewEngines.Engines.FindView(ControllerContext, viewName, masterName);

ViewContext viewContext = new ViewContext(ControllerContext, result.View, viewData, tempData);
result.View.Render(viewContext, output);

result.ViewEngine.ReleaseView(ControllerContext, result.View);

string viewOutput = output.ToString();

I'll leave viewData / tempData to you.