2012-01-22 97 views
9

是否可以訪問未在用戶控件中定義的屬性?我想添加任何html屬性,而不用在代碼隱藏中定義它。asp.net UserControl屬性

例如:

<my:TextBox runat="server" extraproperty="extravalue" /> 

凡在用戶控件沒有定義extraporperty,但仍然會產生:

<input type="text" extraproperty="extravalue" /> 

我需要這在自定義用戶控件。注意我的:在文本框之前。

ty!

+0

你的.ascx看起來像什麼? –

回答

7

是的,這是可能的。去嘗試一下!

例如,

<asp:TextBox ID="MyTextBox" runat="server" extraproperty="extravalue" /> 

呈現爲:

<input name="...$MyTextBox" type="text" id="..._MyTextBox" extraproperty="extravalue" /> 

編輯

從評論:

ASP:文本框不是自定義用戶控制

以上將適用於自定義服務器控件(派生自WebControl),但不適用於UserControl,因爲UserControl沒有可放置該屬性的標籤:它只呈現其內容。

因此,您需要在UserControl類中的代碼將您的自定義屬性添加到其子控件之一。 UserControl然後可以將自定義屬性作爲屬性公開,如下所示:

// Inside the UserControl 
public string ExtraProperty 
{ 
    get { return myTextBox.Attributes["extraproperty"]; } 
    set { myTextBox.Attributes["extraproperty"] = value; } 
} 

// Consumers of the UserControl 
<my:CustomUserControl ... ExtraProperty="extravalue" /> 
+2

asp:文本框不是自定義用戶控件 – LZW

+0

LZW所以呢? – Evgeny

4

實際上,您不必聲明屬性即可將它們用作屬性。就拿這個非常簡單的例子:

<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %> 
<%@ Register TagPrefix="uc" TagName="Test" Src="~/UserControls/Test.ascx" %> 

<uc:Test runat="server" extraproperty="extravalue" /> 

內,您的用戶控件的代碼文件,你可以從任何像這樣的屬性獲得的價值:

protected void Page_Load(object sender, EventArgs e) 
{ 
    string p = Attributes["extraproperty"]; 
} 

正如你所看到的,是把你的用戶的所有屬性控制可以通過Attributes集合使用屬性的名稱作爲從集合中獲取值的關鍵字來讀取。

0

是的,看看IAttributeAccessor界面。 ASP.NET UserControl對象顯式實現此接口。這允許將直接添加到標記中的控件的任何屬性傳送到服務器端屬性集合。

請注意,UserControl上的默認實現不可覆蓋,但可以從其內部屬性集合中讀寫。爲了使這些屬性爲HTML在你的用戶控件,這樣做的標記:

<div runat="server" ID="pnlOutermostDiv"> 
// control markup goes here 
</div> 

然後在用戶控件的代碼隱藏做這樣的事情:

protected override void OnPreRender(EventArgs e) 
{ 
    foreach (string key in Attributes.Keys) 
    { 
     pnlOutermostDiv.Attributes.Add(key, Attributes[key]); 
    } 

    base.OnPreRender(e); 
} 

現在,當你使用這樣的控制:

<my:TextBox runat="server" extraproperty="extravalue" /> 

,它將使這樣的:

<div id="ctl00_blablabla_blablabla" extraproperty="extravalue"> 
// rendered control HTML here 
</div>