Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting a Custom Attribute on a list item in an HTML Select Control (.NET/C#)

Tags:

c#

.net

asp.net

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!

like image 489
kirkyoder Avatar asked Nov 03 '11 05:11

kirkyoder


1 Answers

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.

like image 84
VinayC Avatar answered Oct 05 '22 01:10

VinayC