我正在尝试使用 .cshtml
模板通过 RazorEngine 发送电子邮件。 their site 上的文档展示如何将它与包含 razor 语法的字符串一起使用。我该如何通过加载 .cshtml
文件来使用它?
这就是我所拥有的
string templatePath = "~/Templates/InitialApplicationBody.cshtml";
var result = Engine.Razor.RunCompile(templatePath, "templateKey", null, viewModel);
最佳答案
从 MVC Controller 中,可以轻松地从 Razor View (CSHTML 文件)生成 HTML。
我已成功使用 Render a view as a string 已接受答案中的代码,将其放入基本 Controller 中。
// Renders a Razor view, returning the HTML as a string
protected string RenderRazorViewToString<T>(string viewName, T model) where T : class
{
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();
}
}
关于asp.net-mvc - 如何使用 RazorEngine 从模板发送电子邮件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37707052/