views:

95

answers:

2

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.

A: 

One way of doing it is adding the custom property in code behind

myCustomControl.Attributes.Add("customproperty", "value");

This should do the job for you.

However, I am interested in knowing how to do it in the server control itself.

iHeartDucks
+4  A: 

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?

AnthonyWJones
Now I feel like a donkey :-)I realized that I'm in fact inheriting from "Control", not "WebControl". We used to inherit from "WebControl" but it was changed to "Control" a while ago for some reason.I believe if I just start inheriting from "WebControl", this issue will just cease to exist.
HaukurHaf