How to generate string from View (.aspx or .ascx)
How can I get the resolved (<%%> resolved) view (aspx开发者_开发百科 or ascx) in a string format? I want to have .ascx file with some <%= ... %>
code blocks and I want to be able to send it as part of e-mail in HTML format. How can I do this with MVC?
Don't do it the hard way, checkout MvcMailer or Postal. It will make your life much easier. And not only that but you will have more time to focusing on solving some real business problems rather than plumbing stuff like this which have already been addressed.
Not sure if this works with partial views, but I use this peace of code to render a view as a string.
public string RenderViewAsString(ControllerContext context, string viewName, object model)
{
if (string.IsNullOrEmpty(viewName))
viewName = context.RouteData.GetRequiredString("action");
var view = ViewEngines.Engines.FindView(context, viewName, null).View;
if (view != null)
{
var sb = new StringBuilder();
using (var writer = new StringWriter(sb))
{
var viewContext = new ViewContext(context, view,
new ViewDataDictionary(model), new TempDataDictionary(), writer);
view.Render(viewContext, writer);
writer.Flush();
}
return sb.ToString();
}
return string.Empty;
}
You can make use of the MailMessage class to generate the mail. You can roll out the email creation logic in a separate custom action filter to keep the controller action lean and the email logic reusable.
[UPDATE] The custom action filter can be like :
public class SendEmailAttribute : ActionFilterAttribute
{
public SendEmailAttribute()
{
//Initialize logic --Dependency injection
}
public override void OnActionExecuted(ActionExecutedContext context)
{
SendMail(context); //Implement email sending logic using MailMessage
}
}
精彩评论