Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add a data-attribute to a dropdown menu with C#

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

like image 265
Jon Harding Avatar asked Aug 06 '12 19:08

Jon Harding


People also ask

How do I create a drop-down menu in HTML and CSS?

Use any element to open the dropdown menu, e.g. a <button>, <a> or <p> element. Use a container element (like <div>) to create the dropdown menu and add the dropdown links inside it. Wrap a <div> element around the button and the <div> to position the dropdown menu correctly with CSS.

How do you create a drop-down list in a dropdown list in HTML?

The <select> element is used to create a drop-down list. The <select> element is most often used in a form, to collect user input. The name attribute is needed to reference the form data after the form is submitted (if you omit the name attribute, no data from the drop-down list will be submitted).


2 Answers

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", "!@*#"}
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>
like image 50
Kyle B. Avatar answered Sep 19 '22 22:09

Kyle B.


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>
like image 23
Jon Harding Avatar answered Sep 17 '22 22:09

Jon Harding