Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rendering a view on-the-fly

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?

like image 565
Jonathan Avatar asked May 22 '26 06:05

Jonathan


1 Answers

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.

like image 152
Richard Szalay Avatar answered May 25 '26 07:05

Richard Szalay



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!