简体   繁体   English

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

[英]ASP.Net MVC Add Items To Bound Dropdownlist

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 eg 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. 我想添加“All”的第三个选项,但我不想将此选项添加到我的数据库中。 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 谢谢

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"] ) %>

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"})

Simple 简单

you can make it as you wish in controller. 你可以按照自己的意愿在控制器中制作它。

and pass it in viewdata. 并在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? 确保你没有在ur db中存储添加的选项,对吗? so before you save it, check option value in action and apply your logic. 所以在保存之前,请检查操作中的选项值并应用逻辑。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM