LoadControl,WebMethod中的usercontrol

时间:2013-04-19 02:53:00

标签: c# asp.net user-controls webmethod

我正在尝试通过WebMethod发送电子邮件。以下是我通常在常规帖子上使用的代码

[WebMethod]
public static void SendEmail(string name, string phone, string emailaddress, string interest, string comments)
{
    var control = LoadControl("~/Shared/Controls/EmailTemplate_PartnerWithUs.ascx");

    StringBuilder sb = new StringBuilder();
    StringWriter sw = new StringWriter(sb);
    Html32TextWriter htw = new Html32TextWriter(sw);

    control.RenderControl(htw);

    sb.Replace("%name%", name);
    sb.Replace("%phone%", phone);
    sb.Replace("%emailaddress%", emailaddress);
    sb.Replace("%interest%", interest);
    sb.Replace("%comments%", comments);
    EmailUtility.SendEmailMessage(SettingsManager.GetContactRecipientEmails(), "CoyleHomeBuyers.com Partner Form", sb.ToString());
}

我得到的错误是:

An object reference is required for the non-static field, method, or property 'System.Web.UI.TemplateControl.LoadControl(string)'

有没有办法在WebMethod中加载此控件?

2 个答案:

答案 0 :(得分:6)

UserControl uc= new UserControl();
Control control = uc.LoadControl("~/Shared/Controls/EmailTemplate_PartnerWithUs.ascx");

答案 1 :(得分:0)

您需要将其转换为控件类型。

例如:

Email_PartnerWithUs control = (Email_PartnerWithUs)LoadControl("~/Shared/Controls/EmailTemplate_PartnerWithUs.ascx");

见这里: http://msdn.microsoft.com/en-us/library/system.web.ui.templatecontrol.loadcontrol(v=VS.71).aspx