Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Allowing any property/attribute on a server/usercontrol

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.

like image 211
HaukurHaf Avatar asked Oct 15 '22 12:10

HaukurHaf


1 Answers

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 of Render if you have one.

Can you add a simple example of the code of a new control that fails to your question?

like image 178
AnthonyWJones Avatar answered Oct 20 '22 10:10

AnthonyWJones