简体   繁体   English

如何使用C#将数据属性添加到下拉菜单

[英]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. 我显然收到错误,因为它无法识别data-siteid。

The list is databound. 该列表是数据绑定的。

Any tips would be handy 任何提示都会很方便

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: 此外,如果这只是不是数据绑定的东西,你可以考虑使用HtmlSelect控件,它也应该工作:

<select id="drp2" runat="server">
  <option data-siteId="2">ABC</option>
  <option data-siteId="3">123</option>
  <option data-siteId="4">@*!&</option>
</select>

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. 这使我不必使用ondatabound事件。

<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>

You can rewrite it with pure html if no events handling is needed: 如果不需要事件处理,您可以使用纯HTML重写它:

    <select>
      <%foreach (var item in DataSource){%>
        <option data-siteid="<%=item.SiteID%>" value="<%=item.Value%>"><%=item.Name%> </option>
      <%}%>
    </select>

I ended up doing this (where ds is the dataset): 我最终做了这个(其中ds是数据集):

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"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM