Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
356 views
in Technique[技术] by (71.8m points)

asp.net - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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>

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...