我想从我的网站发送一些邮件。
我创建了一个模板:OrderPlacedEmail.cshtml
@model OnlineCarStore.Models.PurchaseVM
<h1>Order Placed Email Notification</h1>
<p>@Model.Comments</p>
Dear @Model.Name,
<h2>Thank you.</h2>
<p>
You’ve made a purchase on <a href="">@Model.Comments</a>
</p>....and so on...
我创建了一个 View 模型,并且像这样使用它:
var template = Server.MapPath("~/Templates/OrderPlaced.cshtml");
var viewModel = new PurchaseVM
{
GuId = new Guid(guidValue),
Name = name,
Address = address,
Phone = phone,
Email = email,
Comments = comments,
Date = DateTime.Now,
CartList = cartList
};
var body = Razor.Parse(template, viewModel);
据我了解,Razor.Parse 方法应该用 View 模型中的值替换模板中的所有详细信息。但是,正文获取模板位置的值,如下所示:
最佳答案
If you wish there is a helper that i use
public static class HtmlOutputHelper
{
public static string RenderViewToString(ControllerContext context,
string viewPath,
object model = null,
bool partial = false)
{
// first find the ViewEngine for this view
ViewEngineResult viewEngineResult = null;
if (partial)
viewEngineResult = ViewEngines.Engines.FindPartialView(context, viewPath);
else
viewEngineResult = ViewEngines.Engines.FindView(context, viewPath, null);
if (viewEngineResult == null)
throw new FileNotFoundException("View cannot be found.");
// get the view and attach the model to view data
var view = viewEngineResult.View;
context.Controller.ViewData.Model = model;
string result = null;
using (var sw = new StringWriter())
{
var ctx = new ViewContext(context, view,
context.Controller.ViewData,
context.Controller.TempData,
sw);
view.Render(ctx, sw);
result = sw.ToString();
}
return result;
}
}
On your controller
var viewModel = new PurchaseVM
{
GuId = new Guid(guidValue),
Name = name,
Address = address,
Phone = phone,
Email = email,
Comments = comments,
Date = DateTime.Now,
CartList = cartList
};
var emailTemplate = "~/Views/Templates/OrderPlaced.cshtml";
var emailOutput = HtmlOutputHelper.RenderViewToString(ControllerContext, emailTemplate, emailModel, false);
关于asp.net-mvc-4 - 使用 Razor 通过模板 MVC 发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43363420/