我可以使用 ASP.Net MVC Razor 视图来生成格式良好的 HTML 正文作为从服务器发送的电子邮件的输入吗? [英] Can I use an ASP.Net MVC Razor view to generate an nicely formatted HTML Body as the input for an email sent from the server?

查看:15
本文介绍了我可以使用 ASP.Net MVC Razor 视图来生成格式良好的 HTML 正文作为从服务器发送的电子邮件的输入吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想利用 Razor 视图的模型绑定/渲染功能为我从 ASP.NET MVC 应用程序发送的电子邮件生成 HTML 正文内容.

I'd like to make use of the Model Binding / Rendering capabilities of a Razor View to generate the HTML Body Content for an email I'm sending from my ASP.NET MVC Application.

有没有办法将视图呈现为字符串而不是将其作为 GET 请求的 ActionResult 返回?

Is there a way to render a view to a string instead of returning it as the ActionResult of a GET request?

为了说明我正在寻找可以执行以下操作的东西...

To illustrate I'm looking for something that will do the following...

    public ActionResult SendEmail(int id)
    {
        EmailDetailsViewModel emailDetails = EmailDetailsViewModel().CreateEmailDetails(id);

        // THIS IS WHERE I NEED HELP...
        // I want to pass my ViewModel (emailDetails) to my View (EmailBodyRazorView) but instead of Rending that to the Response stream I want to capture the output and pass it to an email client.
        string htmlEmailBody = View("EmailBodyRazorView", emailDetails).ToString();

        // Once I have the htmlEmail body I'm good to go.  I've got a utilityt that will send the email for me.
        MyEmailUtility.SmtpSendEmail("stevejobs@apple.com", "Email Subject", htmlEmailBody);

        // Redirect another Action that will return a page to the user confirming the email was sent.
        return RedirectToAction("ConfirmationEmailWasSent");
    }

推荐答案

如果您只需要将视图呈现为字符串,请尝试以下操作:

If you just need to render the view into a string try something like this:

public string ToHtml(string viewToRender, ViewDataDictionary viewData, ControllerContext controllerContext)
{
    var result = ViewEngines.Engines.FindView(controllerContext, viewToRender, null);

    StringWriter output;
    using (output = new StringWriter())
    {
        var viewContext = new ViewContext(controllerContext, result.View, viewData, controllerContext.Controller.TempData, output);
        result.View.Render(viewContext, output);
        result.ViewEngine.ReleaseView(controllerContext, result.View);
    }

    return output.ToString();
}

您需要从控制器操作中传入视图名称以及 ViewData 和 ControllerContext.

You'll need to pass in the name of the view and the ViewData and ControllerContext from your controller action.

这篇关于我可以使用 ASP.Net MVC Razor 视图来生成格式良好的 HTML 正文作为从服务器发送的电子邮件的输入吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆