我有一些具有不可预测属性的对象,我想使用Mustache.js在电子邮件中呈现HTML内容以将其发送到我的用户的电子邮件。这是我的代码:
在我的HomeController中
public ActionResult Index()
{
Person person = new Person
{
Name = "Dona",
Email = "dona3315@gmail.com",
};
PartialViewResult path = PartialView("PartialViewEmail");
string tmp = path.ViewName;
string resultRenderHtmlEmail = RenderRazorViewToString(tmp, person);
return View();
}
public ActionResult PartialViewEmail(Person model )
{
return PartialView(model);
}
public string RenderRazorViewToString(string viewName, object model)
{
ViewData.Model = model;
using (var sw = new StringWriter())
{
var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
viewResult.View.Render(viewContext, sw);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
这是我的PartialViewEmal.cshtml
@model MvcApplication1.Models.Person
<script src="~/Scripts/mustache.js"></script>
<h1>This is razor partial view that demo for body of email</h1>
I'm @Model.Name and I'm @Model.Email years old.
<div id="sampleArea">
</div>
<script type="text/javascript">
$(function() {
var data = {
employees: [
{
firstName: "Christophe",
lastName: "Coenraets"
},
{
firstName: "John",
lastName: "Smith"
}
]
};
var template = "Employees:<ul>{{#employees}}" +
"<li>{{firstName}} {{lastName}}</li>" +
"{{/employees}}</ul>";
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
</script>
这是resultRenderHtmlEmail:
的结果<script src="/Scripts/mustache.js"></script>
<h1>This is razor partial view that demo for body of email</h1>
I'm Dona and I'm dona3315@gmail.com years old.
<div id="sampleArea">
</div>
<script type="text/javascript">
$(function() {
var data = {
employees: [
{
firstName: "Christophe",
lastName: "Coenraets"
},
{
firstName: "John",
lastName: "Smith"
}
]
};
var template = "Employees:<ul>{{#employees}}" +
"<li>{{firstName}} {{lastName}}</li>" +
"{{/employees}}</ul>";
var html = Mustache.to_html(template, data);
$('#sampleArea').html(html);
});
</script>
它不懂mustache.js!
我该怎么办?
非常感谢!
答案 0 :(得分:1)
如您所知,javascript代码在客户端执行。但邮件客户端和邮件服务不支持电子邮件中的可执行代码。
Razor视图引擎也不支持执行js。因此,您无法使用任何js模板将您的电子邮件模板化。