允许服务器/用户控件上的任何属性/属性
我注意到,在 System.Web.UI.WebControls 命名空间中的大多数(如果不是全部)标准 Web 控件上,您可以向它们添加所需的任何属性,而不会导致页面崩溃。
以 asp:Button 控件为例。
这段代码完全有效:
<form runat="server">
<asp:Button runat="server" Text="Test button" crapAttribute="crapValue" />
</form>
现在,我有一个自定义服务器控件,如果我向它添加任意属性,它就会崩溃。它只接受定义了相应公共属性的属性。
我得到的错误是这样的“该控件没有名为“crapAttribute”的公共属性”。
我希望我的自定义控件接受任何属性而不崩溃。我需要做什么才能使其发挥作用?
我查看了 Reflector 中的标准控件,它们确实具有各种属性和内容,但没有任何东西立即引起我的注意。
我的自定义控件继承了 WebControl 的价值。
I've noticed that on most, if not all, standard web controls in the System.Web.UI.WebControls namespace, you can add any properties you want to them without crashing the page.
Take the asp:Button control for an example.
This code is perfectly valid:
<form runat="server">
<asp:Button runat="server" Text="Test button" crapAttribute="crapValue" />
</form>
Now, I've got a custom server control which crashes if I add arbitrary attributes to it. It only accepts attributes which have a corresponding public property defined.
The error I get is something like this "The control does not have a public property named "crapAttribute" ".
I would like my custom controls to accept any attribute without crashing. What do I need to do for that to work?
I've looked at the standard controls in Reflector and they do have all kinds of attributes and stuff but there was nothing that I saw which immediately caught my eye.
My custom controls are inheriting from WebControl for what it's worth.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不必做任何特别的事情来允许将任意属性添加到控件标记中。从 WebControl 派生的事物通常会获取这些属性并将它们转储到 Attributes 集合中。
我想不出这会失败的原因。如果您有的话,您必须记住在
Render
实现中渲染Attributes
集合。您能否添加一个无法解决您的问题的新控件的代码的简单示例?
You don't have to do anything in particular to allow arbitary attributes to be added the control markup. Things deriving from WebControl would normally scoop up these attributes and dump them in the Attributes collection.
I can't think of reason why this would fail. You would have to remember to render the
Attributes
collection in your implementation ofRender
if you have one.Can you add a simple example of the code of a new control that fails to your question?
一种方法是在代码后面添加自定义属性,
这应该可以为您完成这项工作。
但是,我有兴趣知道如何在服务器控件本身中执行此操作。
One way of doing it is adding the custom property in code behind
This should do the job for you.
However, I am interested in knowing how to do it in the server control itself.