将PartialView内容作为电子邮件发送

时间:2013-04-10 18:47:54

标签: c# asp.net-mvc-3 sendmail asp.net-mvc-partialview

我有一个PartialView,其中包含带有Razor注释的HTML代码。它会向我生成一个我想通过电子邮件发送给任何人的页面。有没有办法将此PartialView转换为HTML内容以发送它?

1 个答案:

答案 0 :(得分:6)

我建议使用 MvcMailer ,它完全符合您的要求(无需为此编写代码..它也可以异步执行):

https://github.com/smsohan/MvcMailer/wiki/MvcMailer-Step-by-Step-Guide

<强>更新

正如评论中所述,自己实施它的解决方案(我仍然认为MvcMailer会让你的生活更轻松):

protected string RenderPartialViewToString(string viewName, object model)
{
    if (string.IsNullOrEmpty(viewName))
        viewName = ControllerContext.RouteData.GetRequiredString("action");

    ViewData.Model = model;

    using (StringWriter sw = new StringWriter()) {
        ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
        ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
        viewResult.View.Render(viewContext, sw);

        return sw.GetStringBuilder().ToString();
    }
}

ASP.NET MVC Razor: How to render a Razor Partial View's HTML inside the controller action