I have a standard dropdown list and am able to databind to the list.
<asp:DropDownList runat="server" ID="ddlMake" ClientIDMode="Static" DataTextField="Name" DataValueField="URL" AppendDataBoundItems="true">
<asp:ListItem>Select Make</asp:ListItem>
</asp:DropDownList>
I would like to add a data-attribute to the option like below:
<asp:ListItem data-siteid="<%# DataBinder.Eval(Container.DataItem, "SiteID") %>">Select Make</asp:ListItem>
I’m obviously getting an error because it doesn’t recognize the data-siteid.
The list is databound.
Any tips would be handy
Answers:
Thank you for visiting the Q&A section on Magenaut. Please note that all the answers may not help you solve the issue immediately. So please treat them as advisements. If you found the post helpful (or not), leave a comment & I’ll get back to you as soon as possible.
Method 1
You could do this in the code-behind. I’m not sure if this is the most elegant approach, but it should work.
Dim dataSrc() As String = {"ABC", "123", "<a href="https://getridbug.com/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="b091f0">[email protected]</a>*#"}
drp.DataSource = dataSrc
drp.DataBind()
For i = 0 To drp.Items.Count - 1
drp.Items(i).Attributes.Add("data-siteId", dataSrc(i))
Next
Also, if this is just something which is not databound, you could consider using the HtmlSelect control which should work as well:
<select id="drp2" runat="server"> <option data-siteId="2">ABC</option> <option data-siteId="3">123</option> <option data-siteId="4">@*!&</option> </select>
Method 2
I ended up using a repeater since the page didn’t need to repost. This allowed me not to have to work with an ondatabound event.
<asp:Repeater runat="server" ID="rptDropDown">
<HeaderTemplate>
<select id="ddlMake">
<option value="">Select Make</option>
</HeaderTemplate>
<ItemTemplate>
<option data-siteid="<%# DataBinder.Eval(Container.DataItem, "SiteID") %>" value="<%# DataBinder.Eval(Container.DataItem, "URL") %>"><%# DataBinder.Eval(Container.DataItem, "Name") %></option>
</ItemTemplate>
<FooterTemplate>
</select>
</FooterTemplate>
</asp:Repeater>
Method 3
You can rewrite it with pure html if no events handling is needed:
<select>
<%foreach (var item in DataSource){%>
<option data-siteid="<%=item.SiteID%>" value="<%=item.Value%>"><%=item.Name%> </option>
<%}%>
</select>
Method 4
I ended up doing this (where ds is the dataset):
for (int row = 0; row <= ds.Tables(0).Rows.Count - 1; row++) {
ddl.Items(row).Attributes.Add("data-siteid", ds.Tables(0).Rows(row)("SiteID"));
}
All methods was sourced from stackoverflow.com or stackexchange.com, is licensed under cc by-sa 2.5, cc by-sa 3.0 and cc by-sa 4.0