ASP.NET MVC dropdown with a default empty option

谁说胖子不能爱 提交于 2020-01-30 14:02:11

问题


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


回答1:


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.

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

Documentation: DropDownList method




回答2:


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 :




回答3:


This easy solution worked for my mvc5 project:

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.




回答4:


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

The basic idea is that you set the AppendDataBoundItems property of your DropDownList to true and then put an asp:ListItem in the DropDownList and that will become your default item with all the databound items coming after it.



来源:https://stackoverflow.com/questions/506001/asp-net-mvc-dropdown-with-a-default-empty-option

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!