asp.net-mvc 带有默认空选项的 ASP.NET MVC 下拉列表

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

ASP.NET MVC dropdown with a default empty option

asp.net-mvchtml.dropdownlistforhtml-select

提问by James Newton-King

Is there a way to include a default empty option (or with text) if there is no selected value for a dropdownlist?

如果下拉列表没有选定的值,有没有办法包含默认的空选项(或带有文本)?

回答by tvanfosson

The below will prepend string.Empty to the SelectList (or IEnumerable) specified in the ViewData["Menu"] item. The select will have id and name MenuID.

下面将在 ViewData["Menu"] 项中指定的 SelectList(或 IEnumerable)前面添加 string.Empty。选择将有 id 和 name MenuID

<%= Html.DropDownList( "MenuID",
                      (IEnumerable<SelectListItem>)ViewData["Menu"],
                      string.Empty ) %>

Documentation: DropDownList method

文档:DropDownList 方法

回答by tiepnv

For Example:

例如:

    Controller :

    private void InitScreenInfoCollate()
    {   
        IEnumerable<MstBrd> listbrd = ibrandRepository.GetItemsByUsercode("");
        ViewBag.Brands = new SelectList(listbrd, "brd_cod", "brd_mei", null);

    }

    View :
    @Html.DropDownList("Brands", null, string.Empty, new { @class = "form-control"})

Result :

结果 :

inline image

内嵌图像

回答by PixelPlex

This easy solution worked for my mvc5 project:

这个简单的解决方案适用于我的 mvc5 项目:

in view:

鉴于:

@{
     Model.ModelItemsList.Add(new ModelItem{ });
     SelectList modelItemSelectList = new SelectList(Model.ModelItemsList, "ModelItemID", "ModelItemName");
}

Just add a new item to the List<>you want to display in your view. In my case, I added a empty "ModelItem" to my List<ModelItem> ModelItemList. Since my ModelItemID is a Guid, I had to check for Guid.Empty in my controller method and do some code. Thats all.

只需向List<>要在视图中显示的新项目添加一个新项目。就我而言,我在我的List<ModelItem> ModelItemList. 由于我的 ModelItemID 是一个 Guid,我必须在我的控制器方法中检查 Guid.Empty 并执行一些代码。就这样。

回答by cjbarth

The solution presented here worked very well for me: http://forums.asp.net/t/1142484.aspx/1

这里提出的解决方案对我来说非常有效:http: //forums.asp.net/t/1142484.aspx/1

The basic idea is that you set the AppendDataBoundItemsproperty of your DropDownListto trueand then put an asp:ListItemin the DropDownListand that will become your default item with all the databound items coming after it.

基本思想是,您设置to的AppendDataBoundItems属性,然后将一个in放入,这将成为您的默认项目,所有数据绑定项目都在它之后。DropDownListtrueasp:ListItemDropDownList