I'm trying to create a custom attribute for each list item in a databound HTML Select control.
The resulting HTML output should look something like this:
<select>
<option value="1" data-value="myValue1">item</option>
<option value="2" data-value="myValue2">item</option>
<option value="3" data-value="myValue3">item</option>
</select>
I've tried adding attributes like this, but they aren't being rendered:
<select id="selectList" class="multiselect" multiple="true" name="selectList[]" runat="server"></select>
ListItemCollection values = new ListItemCollection();
ListItem test = new ListItem("add");
test.Attributes.Add("data-value", "myValue");
values.Add(test);
this.selectList.DataSource = values;
this.selectList.DataBind();
Any thoughts on how this can be achieved? Thanks!
You have to add attributes to control's list items. Data-binding the list control may only set name & text. So simplest way is to add items manually instead of data-binding - for example:
ListItem test = new ListItem("text1", "value1");
test.Attributes.Add("data-value", "myValue1");
applicationList.Items.Add(test);
If you must use data-binding then you have to handle DataBound event and then iterate over the control's list items and add/set the required attribute. Frankly, I found this to be a round-about way of doing things.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With