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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3276798/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-29 03:48:52  来源:igfitidea点击:

ASP.NET DropDownList / HTML select list default selection

asp.nethtmlselectdrop-down-menuselectedindex

提问by harrije

For my ASP.NET page, in the code behind I load various items/options into a DropDownList but I do not set a default by assigning SelectedIndex. I notice for the postback SelectedIndex is set to 0, even if I never set focus to or changed the value in the DropDownList.

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

If not otherwise specified in the code behind or markup, will a default value of 0 be used for the SelectedIndex in a postback with a DropDownList? If yes, is this part of the HTML standard for selection lists, or is this just the way it is implemented for ASP.NET?

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

回答by Marko

This is normal behavior for the HTML SELECTcontrol.

这是 HTMLSELECT控件的正常行为。

Unless the selected property is used, it will always start at the first item (index of 0).

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

In many cases, I don't want this in ASP.NET because I specifically want the user to select an option.

在许多情况下,我不希望在 ASP.NET 中这样做,因为我特别希望用户选择一个选项。

So what I do is add a blank item which I can then validate.

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

i.e.

IE

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

This way, I can set a validator which checks if the value is blank, forcing the user to make a selection.

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

回答by KyleMit

For anybody looking for a way to do this from the code behind, you can add the extra list item there by using the Insertfunction and specifying an Indexof 0, as mentioned in this SO Question. Just make sure to do so after you've called DataBind()

对于任何从背后的代码中寻找方法来执行此操作的人,您可以通过使用该Insert函数并指定Index0来添加额外的列表项,如本SO Question 中所述。只要确保在你打电话后这样做DataBind()

myDropDownList.DataSource = DataAccess.GetDropDownItems(); // Psuedo Code
myDropDownList.DataTextField = "Value";
myDropDownList.DataValueField = "Id";
myDropDownList.DataBind();

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