LoadControl, usercontrol in WebMethod

狂风中的少年 提交于 2019-12-23 09:33:19

问题


I am trying to send an email through a WebMethod Below is the code I typically use on a regular post back

[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());
}

The error I'm getting is:

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

Is there a way to load this control within the WebMethod?


回答1:


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



回答2:


You need to cast it into a control type.

For example:

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

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



来源:https://stackoverflow.com/questions/16096458/loadcontrol-usercontrol-in-webmethod

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!