I am using dropdownlist in asp.net, it has collection of ListItem that represents the items of the dropdownlist, each ListItem has only two fields to hold the data, Value and Text fields, but those are not enough I would like to hold more data for each item. Let's say Text1 and Text2 in additional fields, but at the same time I would like to preserve the same behavior of the DataBind() method of the dropdownlist.

有帮助吗?

解决方案

Sure, you can use the Attributes collection:

ListItem li = new ListItem("myText", "myID");
li.Attributes.Add("data-x", "xx");
dropdown.Items.Add(li);

This will give you this HTML:

<select name="dropdown" id="dropdown">
   <option value="myID" data-x="xx">myText</option>
</select>

I suggest you prefix your custom attributes with "data-": http://html5doctor.com/html5-custom-data-attributes/

其他提示

If you want to be able to preserve the items, try setting the AppendDataBoundItems property to true. Then you can programmatically add more items:

dropDown.Items.Add("Another Item", "2");

and preserve the original ones.

许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top