如何在ASP.Net中将自定义文本设置为DropdownList

RBS*_*RBS 1 asp.net drop-down-menu

我在我的一个应用程序中有下拉列表控件,当我从数据库中添加项目时它默认显示第一个项目到下拉列表但我想显示其他文本,如"从列表中选择项目"有什么办法吗?我可以做这个 .

还能请你帮我设置javascript的相同值

pat*_*dge 7

在ASP.NET方面,您可以使用AppendDataBoundItems ="true"创建DropDownList,并且绑定到它的任何项都将在默认值之后:

<asp:DropDownList AppendDataBoundItems="true" ID="yourListId" runat="server">
    <asp:ListItem Text="Select something" Value="-1" />
</asp:DropDownList>
Run Code Online (Sandbox Code Playgroud)

至于在Javascript中完全做同样的事情,你可以用这样的函数来做:

function addFirstItem(list, text, value)
{
    var newOption = document.createElement("option");
    newOption.text = text;
    newOption.value = value;
    list.options.add(newOption);
}

addFirstItem(document.getElementById("yourListId"), "Select something", "-1");
Run Code Online (Sandbox Code Playgroud)

或者使用jQuery(可能有更简洁的东西,特别是对于创建一个新的选项标签,但这有效):

$("#yourListId option:first").before("<option value='-1'>Select something</option>");
Run Code Online (Sandbox Code Playgroud)