设置’cshtml’数据并返回一个字符串

我有一个确认电子邮件模板.cshtml如下:

   company name: Email Verification - Action Required    Thanks for signing up for company name! 

Thank you for signing up to company name. Please press the link below to confirm your email address
If you did not sign up for company name, please ignore this email, and accept our apologies for the inconvenience.

https://stackoverflow.com/questions/33463224/set-cshtml-data-and-return-a-string/@Model.ConfirmLink


Thanks,
The company name Team

有没有一种机制可以设置数据( https://stackoverflow.com/questions/33463224/set-cshtml-data-and-return-a-string/@Model.ConfirmLink )并以string返回结果? (不是手动替换字符串)

您可以使用RazorEngine ,它使用与Razor相同的语法,但是您可以在不需要ASP.NET MVC的情况下呈现文本。

您的代码如何工作:

 string template = yourHtmlCodeAsString; string result = Razor.Parse(template, new { ConfirmLink = "http://.../" }); 

您可以从文件,资源等加载该模板字符串。

是的,您可以将Razor用作电子邮件的模板引擎。

我用这个class。

 public static class EmailFactory { public static string ParseTemplate(T model, string templatesPath, EmailType emailType) { string templatePath = Path.Combine(templatesPath, string.Format("{0}.cshtml", emailType)); string content = templatePath.ReadTemplateContent(); return Razor.Parse(content, model); } } 
  • templatesPath – 是我的电子邮件cshtml视图的路径。
  • EmailType是和enum,其元素与templatesPath目录中的视图namse相同。

本质是Razor.Parse(content, model); 它需要一个有效的剃刀视图和模型的字符串,并将它们合并在一起。 与ASP MVC中的视图相同。