LZW*_*LZW 9 c# asp.net user-controls
是否可以访问未在用户控件中定义的属性?我想添加任何html属性而不在codebehind中定义它.
例如:
<my:TextBox runat="server" extraproperty="extravalue" />
Run Code Online (Sandbox Code Playgroud)
其中extraporperty未在用户控件中定义,但仍会生成:
<input type="text" extraproperty="extravalue" />
Run Code Online (Sandbox Code Playgroud)
我需要在自定义用户控件中使用它.注意my:在文本框之前.
TY!
是的,这是可能的.就试一试吧!
例如,
<asp:TextBox ID="MyTextBox" runat="server" extraproperty="extravalue" />
Run Code Online (Sandbox Code Playgroud)
呈现为:
<input name="...$MyTextBox" type="text" id="..._MyTextBox" extraproperty="extravalue" />
Run Code Online (Sandbox Code Playgroud)
编辑
来自评论:
asp:textbox不是自定义用户控件
以上内容适用于自定义服务器控件(派生自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" />
Run Code Online (Sandbox Code Playgroud)
实际上,您不必声明属性即可将其用作属性。举一个非常简单的例子:
<%@ Page Language="C#" CodeFile="Default.aspx.cs" Inherits="_Default" %>
<%@ Register TagPrefix="uc" TagName="Test" Src="~/UserControls/Test.ascx" %>
<uc:Test runat="server" extraproperty="extravalue" />
Run Code Online (Sandbox Code Playgroud)
在用户控件的代码文件中,您可以从任何属性中获取值,如下所示:
protected void Page_Load(object sender, EventArgs e)
{
string p = Attributes["extraproperty"];
}
Run Code Online (Sandbox Code Playgroud)
如您所见,可以Attributes使用属性名称作为从集合中获取值的键,在集合中读取用户控件上放置的所有属性。