【问题标题】:Usercontrol render with object asp.net C#使用对象 asp.net C# 渲染用户控件
【发布时间】:2011-08-03 09:51:26
【问题描述】:

我正在处理一个需要发送电子邮件的项目。邮件格式已在 ascx 用户控件中制作,该控件将用于呈现电子邮件正文,其中某些变量(例如名称和日期)是通过另一种方法填充的。

我的主要问题是我想在电子邮件正文中呈现控件以及类和方法的对象。其实我想以 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;
}

【问题讨论】:

    标签: c# asp.net-mvc email ascx


    【解决方案1】:

    我不确定我是否完全掌握了您想要的内容,但您可以尝试使用所有控件公开的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();
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-25
      • 2017-09-13
      相关资源
      最近更新 更多