2010-09-19 57 views
2

我使用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一些參數,但我真的不知道如何使用它,非常感謝!

回答

10

你可以在你的usercontrol上爲相應的參數實現一個接口。

public interface ICustomParams 
{ 
    string UserName { get; set; } 
    DateTime SelectedDate { get; set; } 
} 

實現該接口的用戶控件,這樣

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; 
    } 

完成,

您可以在其中添加多個用於多種用途的接口。 如果用戶控件沒有實現接口,if語句將避免使用它

但是,如果您確實無法訪問usercontrols,並且您知道要設置的屬性的「一小部分」以及嘗試使用哪種類型與反射的更動態的方式:

負載該用戶控件:

UserControl userControl = (UserControl)Page.LoadControl(@"~/WebUserControl.ascx"); 

獲取所加載的用戶控件的屬性:

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; 
      } 
     } 
    } 

我只會鼓勵你這個,如果你不能訪問用戶控件並有幾十人,有很多很多的用戶控件每個變量的屬性。 (它可能會變得非常難看,速度慢並且不安全)

+0

完美!只是我需要的東西,它的工作原理,非常感謝你! – Martin 2010-09-19 19:14:34

+0

增加了一些額外的東西,但現在看起來已經過時;)請不要使用反射的東西... – 2010-09-19 19:33:44

1

我不知道它是如何一般地完成的,但它看起來像是加載自己的用戶控制。例如,嘗試將UserControl轉換爲您正在使用的控件的類型。

// Create instance of the user control 
    MyUserControl userControl = (MyUserControl)page.LoadControl("/MyUserControl.ascx"); 

    userControl.Param1="my param"; 
+0

謝謝,但我的問題是我使用一個函數來獲取多個用戶控件的內容。所以我並不總是知道用戶控件的名稱,只是它的路徑。我已更新我的問題以反映這一點。 – Martin 2010-09-19 17:55:39