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

har*_*ije 3 html asp.net select selectedindex drop-down-menu

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

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

Mar*_*rko 5

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

除非使用selected属性,否则它将始终从第一项(索引为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>
Run Code Online (Sandbox Code Playgroud)

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