ASP.NET DropDownList / HTML选择列表默认选择

时间:2010-07-18 18:53:25

标签: asp.net html select drop-down-menu selectedindex

对于我的ASP.NET页面,在后面的代码中我将各种项目/选项加载到DropDownList中,但是我没有通过分配SelectedIndex来设置默认值。我注意到postback的SelectedIndex设置为0,即使我从未设置焦点或更改DropDownList中的值。

如果在后面的代码或标记中没有另外指定,在使用DropDownList的回发中,是否将默认值0用于SelectedIndex?如果是,这是选择列表的HTML标准的一部分,还是这就是它为ASP.NET实现的方式?

2 个答案:

答案 0 :(得分:5)

这是HTML SELECT控件的正常行为。

除非使用了所选属性,否则它将始终从第一项开始(索引为0)。

在很多情况下,我不希望在ASP.NET中使用它,因为我特别希望用户选择一个选项。

所以我做的是添加一个空白项目,然后我可以验证。

<asp:DropDownList runat="server" DataSourceID="SomeDS" AppendDataBoundItems="true"> // Notice the last property
    <asp:ListItem Text="Please select an option" Value="" />
</asp:DropDownList>

这样,我可以设置一个验证器,检查该值是否为空,强制用户进行选择。

答案 1 :(得分:2)

对于任何想要从后面的代码中执行此操作的方法的人,您可以使用Insert函数添加额外的列表项,并指定Index为0,如此处所述{ {3}}。在致电DataBind()

之后,请务必确保这样做
myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
myDropDownList.DataTextField = "Value";
myDropDownList.DataValueField = "Id";
myDropDownList.DataBind();

myDropDownList.Items.Insert(0, new ListItem("Please select", ""));