我想在我的剃刀模板基类上设置与电子邮件相关的属性,可用于发送带有渲染模板的电子邮件。
如何获得对已编译模板的引用?
答案 0 :(得分:1)
不,你不能,这是设计的。 但您可能想要执行以下操作:
public class EmailDataHolder {
public string Destination { get; set; }
public string Subject { get; set; }
}
// In the custom TemplateBase class:
public class EmailTemplateBase<T> : TemplateBase<T>
{
public EmailDataHolder EmailProperties { get { return Viewbag.DataHolder; } }
// Or for even simpler templates
//public string Subject { get { return Viewbag.DataHolder.Subject; }; set { Viewbag.DataHolder.Subject = value; } }
}
// Your code
public static Task SendEmailAsync<T>(string templateName, string destination, T model)
{
var holder = new EmailDataHolder();
dynamic viewbag = new DynamicViewBag();
viewbag.DataHolder = holder;
holder.Destination = destination;
var body = Engine.Razor.Run(templateName, typeof(T), model, (DynamicViewBag)viewbag);
MailMessage msg = new MailMessage();
msg.To.Add(new MailAddress(holder.Destination));
msg.Subject = holder.Subject;
msg.AlternateViews.Add(AlternateView.CreateAlternateViewFromString(body, null, MediaTypeNames.Text.Html));
SmtpClient smtpClient = new SmtpClient();
return smtpClient.SendMailAsync(msg);
}
如果您想使用@model
,您希望将RazorEngine配置为使用此自定义TemplateBase
实施:
config.BaseTemplateType = typeof(EmailTemplateBase<>);
然后你可以像这样使用它:
@inherits EmailTemplateBase<HelloWorldModel>
@{
Layout = "CI";
EmailProperties.Subject = "Hello World";
// with the simpler version
//Subject = "Hello World";
}
Hello @Model.Name,<br/>
this is a test email...
虽然这并没有真正为您提供编译模板的参考,但它允许您在模板中保存数据并在以后使用它。