我正在处理一个需要发送电子邮件的项目。邮件格式是在ascx
Usercontrol中进行的,该控件将用于呈现电子邮件正文,其中某些变量(如名称和日期)是从其他方法填充的。
我的主要问题是我想在电子邮件正文中呈现控件以及类和方法的对象。实际上我想以MVC的方式做到这一点(即在前端传递模型。)有没有什么好方法可以做到这一点?
我使用的代码如下:
string path = "Email Template/LeaveRequestedEmailToAPPREC.ascx";
body = RenderUserControl(path,lrd);
MailMessage msg = new MailMessage();
try
{
msg.From = new MailAddress(fromemail, fromname);
msg.To.Add(toemail);
msg.Subject = subject;
msg.Body = body;
msg.IsBodyHtml = true;
SmtpClient sc = new SmtpClient();
sc.Host = "smtp.ntc.net.np";
sc.Port = 25;
sc.Send(msg);
msg.Dispose();
msg = null;
return true;
}
//======== Rendering the UserControl ==========
public string RenderUserControl(string path,object viewmodel)
{
Page holder = new Page();
UserControl viewControl = (UserControl)holder.LoadControl(path);
HtmlForm tempForm = new HtmlForm(); //if the UserControl contain some server controls like TextBox, Button, Add a form wrapped them.
tempForm.Controls.Add(viewControl);
holder.Controls.Add(tempForm);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(holder, output, false);
string outputToReturn = output.ToString();
output.Close();
return outputToReturn;
}
答案 0 :(得分:0)
我不确定我是否完全掌握了您想要的内容,但您可以尝试使用所有控件公开的RenderControl方法,例如:
using (var buffer = new MemoryStream())
{
var builder = new System.IO.StreamWriter(buffer);
using (var stream = new HtmlTextWriter(builder))
{
holder.RenderControl(stream);
}
return builder.ToString();
}