ASP.NET UserControl 属性

12

是否可以访问在用户控件中未定义的属性?我想要添加任何HTML属性而无需在CodeBehind中定义它。

例如:

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

在用户控件中未定义extraporperty,但仍会生成:

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

我需要在自定义用户控件中实现这个功能。注意文本框前面的 my:。

谢谢!


你的 .ascx 长什么样? - Michael Liu
4个回答

9
您实际上不需要声明属性即可将其用作属性。看这个非常简单的例子:
<%@ 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集合中读取值来访问。


9

是的,这是可能的。只需尝试一下!

例如,

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

渲染为:

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

编辑

来自评论:

asp:textbox 不是自定义用户控件

上述内容适用于自定义服务器控件(派生自 WebControl),但不适用于用户控件,因为用户控件没有标签可以放置属性:它只呈现其内容。

因此,您需要在用户控件类中编写代码,将自定义属性添加到其子控件之一。然后,用户控件可以将自定义属性公开为属性,例如:

// 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:textbox不是自定义用户控件。 - LZW

2

1

是的,请看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>

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接