C# ASP.Net MVC 添加项目到绑定下拉列表

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

ASP.Net MVC Add Items To Bound Dropdownlist

c#asp.net-mvcdrop-down-menu

提问by Gavin

My page view currently has a dropdownlist on it that is getting bound to a collection from the controller. This is working fine, However I want to insert an item to the top of the dropdownlist that is not in my collection e.g the list currently gets the following items

我的页面视图目前有一个下拉列表,它绑定到控制器的集合。这工作正常,但是我想在下拉列表的顶部插入一个不在我的集合中的项目,例如列表当前获取以下项目

Open
Closed

I want to add a third option of "All" but I don't want to add this option to my database. In Webforms I would have just bound the control then inserted another item however it seems this is not possible with MVC, am I right in thinking I will need to add some Javascript to the view to add this new item once the dropdownlist has been bound?

我想添加“全部”的第三个选项,但我不想将此选项添加到我的数据库中。在 Webforms 中,我只是绑定了控件然后插入了另一个项目,但是似乎这在 MVC 中是不可能的,我是否认为我需要在视图中添加一些 Javascript 以在绑定下拉列表后添加这个新项目?

Thanks

谢谢

采纳答案by tvanfosson

No. Construct your data as a list of SelectListItems and prepend in the controller.

不。将您的数据构建为 SelectListItems 列表并在控制器中添加。

   var list = db.Table
                .Select( t => new SelectListItem
                              { 
                                  Key = t.ID.ToString(),
                                  Value = t.Name
                              } )
                .ToList();
   list.Insert( 0, new SelectListItem { Key = "-1", Value = "All" } );

   ViewData["TableSelect"] = list;

On the view side:

在视图方面:

   <%= Html.DropDownList( "TableID",
                          (IEnumerable<SelectListItem>)ViewData["TableSelect"] ) %>

回答by Vikas

Simple

简单的

you can make it as you wish in controller.

您可以在控制器中随心所欲地制作它。

and pass it in viewdata.

并在视图数据中传递它。

other option is directly in view page.

其他选项直接在视图页面中。

<%= Html.DropDownList("DropDown","all" )%>

But you can add only one option..

但是您只能添加一个选项..

Make sure you are not storing added options in ur db, right? so before you save it, check option value in action and apply your logic.

确保您没有在您的数据库中存储添加的选项,对吗?因此,在保存之前,请检查操作中的选项值并应用您的逻辑。

回答by Denis Cilliers

Newer implementation

较新的实现

var list = _db.Status.ToList();
list.Add(new Status(){DevelopmentStatusID = -1, DevelopmentStatusDesc = "All"});
var result = list.OrderBy(d => d.StatusID).ToList();

ViewBag.StatusID = new SelectList(result, "StatusID", "StatusDesc");

Then in the index.html

然后在 index.html

    @Html.DropDownList("StatusID", null, htmlAttributes: new {@class = "form-control"})