将参数发送到动态加载的用户控件

我使用jQuery将一些用户控件的内容加载到我的页面中。所以我有这个功能从我的用户控件中提取内容,它就像一个魅力。
    public string GetObjectHtml(string pathToControl)
    {
        // Create instance of the page control
        Page page = new Page();

        // Create instance of the user control
        UserControl userControl = (UserControl)page.LoadControl(pathToControl);

        //Disabled ViewState- If required
        userControl.EnableViewState = false;

        //Form control is mandatory on page control to process User Controls
        HtmlForm form = new HtmlForm();

        //Add user control to the form
        form.Controls.Add(userControl);

        //Add form to the page
        page.Controls.Add(form);

        //Write the control Html to text writer
        StringWriter textWriter = new StringWriter();

        //execute page on server
        HttpContext.Current.Server.Execute(page, textWriter, false);

        // Clean up code and return html
        string html = CleanHtml(textWriter.ToString());

        return html;
    }
但我真的想在创建时将一些参数发送到我的用户控件中。这可能吗,我该怎么做? 我可以看到
LoadControl()
可以用
object[] parameters
取一些参数,但我真的不确定如何使用它,非常感谢!     
已邀请:
您可以在usercontrol上为适当的参数实现一个接口。
public interface ICustomParams
{
    string UserName { get; set; }
    DateTime SelectedDate { get; set; }
}
像这样在usercontrol中实现接口
public partial class WebUserControl : System.Web.UI.UserControl , ICustomParams
{
    public string UserName { get; set; }
    public DateTime SelectedDate  { get; set; }
}
然后加载你的控件:
  UserControl userControl = (UserControl)page.LoadControl(pathToControl);
通过界面访问控件
  ICustomParams ucontrol = userControl as ICustomParams;
  if(ucontrol!=null)
  {
       ucontrol.UserName = "henry";
       ucontrol.SelectedDate = DateTime.Now;
  }
做完后, 您可以在那里添加多个用于多种用途的接口。 如果usercontrol没有实现接口,则if语句将避免使用它 但是,如果您真的无法访问用户控件并且您知道要设置的“一点”属性以及它们的类型,请尝试使用反射的更动态的方式: 加载usercontrol:
    UserControl userControl = (UserControl)Page.LoadControl(@"~/WebUserControl.ascx");
获取加载的usercontrol的属性:
    PropertyInfo[] info = userControl.GetType().GetProperties();
循环通过它:
    foreach (PropertyInfo item in info)
    {
        if (item.CanWrite)
        {
             switch (item.Name)
             {
                 case "ClientName"
                     // A property exists inside the control": //
                     item.SetValue(userControl, "john", null); 
                     // john is the new value here
                 break;
             }
        }
    }
如果你不能访问用户控件,我会鼓励你这个,并且每个用户控件有很多很多很多变量属性。 (它可能变得非常丑陋,缓慢而且不是故障安全的)     
我不确定如何一般地完成它,但看起来你正在加载自己的用户控件。例如,尝试将UserControl转换为您正在使用的控件的类型。
 // Create instance of the user control 
    MyUserControl userControl = (MyUserControl)page.LoadControl("/MyUserControl.ascx"); 

  userControl.Param1="my param";
    

要回复问题请先登录注册