asp.net-mvc 将空值添加到 ASP.net MVC 中的 DropDownList

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/942262/
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-09-07 23:37:26  来源:igfitidea点击:

Add empty value to a DropDownList in ASP.net MVC

asp.net-mvcvb.netdrop-down-menu

提问by jvanderh

I'm building a data entry interface and have successfully bound the columns that have reference tables for their data using DropDownList so the user selects from the pre-configured values.

我正在构建一个数据输入界面,并使用 DropDownList 成功绑定了具有数据引用表的列,以便用户从预配置的值中进行选择。

My problem now is that I don't want the first value to be selected by default, I need to force the user to select a value from the list to avoid errors where they didn't pick that field and by default a value was assigned.

我现在的问题是我不希望默认情况下选择第一个值,我需要强制用户从列表中选择一个值以避免错误,因为他们没有选择该字段并且默认情况下分配了一个值.

Is there a more elegant way of doing this than to add code to include an empty value at the top of the list after I get it from the database and before i pass it to the SelectList constructor in my controller class?

有没有比在我从数据库中获取空值之后以及将它传递给控制器​​类中的 SelectList 构造函数之前添加代码以在列表顶部包含一个空值更优雅的方法?

回答by Ropstah

The Html helper function takes a 'first empty value' parameter as the third argument.

Html 辅助函数将“第一个空值”参数作为第三个参数。

<%=Html.DropDownList("name",dataSource,"-please select item-")%>

回答by qulzam

You can also use this way:

您也可以使用这种方式:

dropdownlist.DataTextField = ds.Tables[0].Columns[0].Caption;
dropdownlist.DataValueField = ds.Tables[0].Columns[1].Caption;
dropdownlist.DataSource = ds;
dropdownlist.DataBind();


dropdownlist.Items.Insert(0, new ListItem("Select ...", string.Empty));