Mathematics
Mathematics

Reputation: 7628

ASP.NET Drop Down List custom attribute

I'm adding a custom attribute to drop down list like this,

 <asp:DropDownList ID="ddlFirst" runat="server" ClientIDMode="Static"></asp:DropDownList>

In code behind I'm adding custom attribute,

ListItem deleteMeLi = new ListItem("Mango", "");
deleteMeLi.Attributes.Add("data-IsMangoRotten", "0");
ddlFirst.Items.Add(deleteMeLi);

Now when I try to get value back like this,

 int rottenM = Convert.ToInt32(ddlFirst.SelectedItem.Attributes["data-IsMangoRotten"].ToString());

It throws object is null expection,

While debugging I figured out that the count of Attributes of ddlFirst are 0, however in HTML I can see the attrbutes using developer tools

Upvotes: 0

Views: 5933

Answers (2)

spongessuck
spongessuck

Reputation: 1073

Your example works fine on its own.

I suspect you're trying to get the SelectedItem's attributes before you've added deleteMeLi to ddlFirst, so then you try to get the attributes of a null object and get the exception.

Check when in the Page life cycle you're adding the ListItem and when you're trying to get the attribute value.

Upvotes: 0

Icarus
Icarus

Reputation: 63966

The problem is that DropDownLists are rendered as <select> elements on the client side, and as such, you cannot add an attribute to an <option> element in HTML and retrieve it on the server-side because they are NOT posted. Sure, you can access them on the client-side via plain Javascript but don't expect them to be posted to the server.

Upvotes: 2

Related Questions