我如何添加一个项目到ASP.net MVC的SelectList
基本上我正在寻找在默认值为0,文本值为“ – select一个 – ”的SelectList开头插入一个项目
就像是
SelectList list = new SelectList(repository.func.ToList()); ListItem li = new ListItem(value, value); list.items.add(li);
可以这样做吗?
除非您坚持0的值,否则实际上不需要这样做.HtmlHelper DropDownList扩展允许您设置选项标签,该标签在select中显示为具有空值的初始值。 只需使用具有选项标签的DropDownList签名之一即可。
<%= Html.DropDownList( "DropDownValue", (IEnumerable<SelectListItem>)ViewData["Menu"], "-- Select One --" ) %>
我得到这个工作,通过填充一个SelectListItem,转换为一个列表,并在索引0添加一个值。
List<SelectListItem> items = new SelectList(CurrentViewSetups, "SetupId", "SetupName", setupid).ToList(); items.Insert(0, (new SelectListItem { Text = "[None]", Value = "0" })); ViewData["SetupsSelectList"] = items;
这个有可能。
//Create the select list item you want to add SelectListItem selListItem = new SelectListItem() { Value = "null", Text = "Select One" }; //Create a list of select list items - this will be returned as your select list List<SelectListItem> newList = new List<SelectListItem>(); //Add select list item to list of selectlistitems newList.Add(selListItem); //Return the list of selectlistitems as a selectlist return new SelectList(newList, "Value", "Text", null);
我喜欢@ AshOoO的答案,但像@Rajan Rawal我需要保留选定的项目状态,如果有的话。 所以我将自定义添加到他的方法AddFirstItem()
public static SelectList AddFirstItem(SelectList origList, SelectListItem firstItem) { List<SelectListItem> newList = origList.ToList(); newList.Insert(0, firstItem); var selectedItem = newList.FirstOrDefault(item => item.Selected); var selectedItemValue = String.Empty; if (selectedItem != null) { selectedItemValue = selectedItem.Value; } return new SelectList(newList, "Value", "Text", selectedItemValue); }
private SelectList AddFirstItem(SelectList list) { List<SelectListItem> _list = list.ToList(); _list.Insert(0, new SelectListItem() { Value = "-1", Text = "This Is First Item" }); return new SelectList((IEnumerable<SelectListItem>)_list, "Value", "Text"); }
这应该做你所需要的,只要发送你的select列表,它会返回一个select列表与索引0中的项目
您可以自定义您需要插入的项目的文本,值或索引
.ToList()。Insert(..)方法将一个元素放入您的List中。 任何位置都可以指定。 ToList之后只需添加.Insert(0,“ – – First Item – – ”)
你的代码
SelectList list = new SelectList(repository.func.ToList()); ListItem li = new ListItem(value, value); list.items.add(li);
新代码
SelectList list = new SelectList(repository.func.ToList().Insert(0, "- - First Item - -")); ListItem li = new ListItem(value, value); list.items.add(li);
可能听起来不太优雅,但我通常做这样的事情:
var items = repository.func.ToList(); items.Insert(0, new funcItem { ID = 0, TextValue = "[None]" }); ViewBag.MyData = new SelectList(items);
这里为你的html助手
public static SelectList IndividualNamesOrAll(this SelectList Object) { MedicalVarianceViewsDataContext LinqCtx = new MedicalVarianceViewsDataContext(); var IndividualsListBoxRaw = ( from x in LinqCtx.ViewIndividualsNames //not correct need individual view! orderby x.FullName select x ); List<SelectListItem> items = new SelectList ( IndividualsListBoxRaw, "First_Hospital_Case_Nbr", "FullName" ).ToList(); items.Insert(0, (new SelectListItem { Text = "All Individuals", Value = "0.0", Selected = true })); Object = new SelectList ( items,"Value","Text" ); return Object; }
好吧,我喜欢干净的代码,所以我做了一个扩展方法
static public class SelectListHelper { static public SelectList Add(this SelectList list, string text, string value = "", ListPosition listPosition = ListPosition.First) { if (string.IsNullOrEmpty(value)) { value = text; } var listItems = list.ToList(); var lp = (int)listPosition; switch (lp) { case -1: lp = list.Count(); break; case -2: lp = list.Count() / 2; break; case -3: var random = new Random(); lp = random.Next(0, list.Count()); break; } listItems.Insert(lp, new SelectListItem { Value = value, Text = text }); list = new SelectList(listItems, "Value", "Text"); return list; } public enum ListPosition { First = 0, Last = -1, Middle = -2, Random = -3 } }
用法(举例):
var model = new VmRoutePicker { Routes = new SelectList(_dataSource.Routes.Select(r => r.RouteID).Distinct()) }; model.Routes = model.Routes.Add("All", "All", SelectListHelper.ListPosition.Random); //or model.Routes = model.Routes.Add("All");
由于这个选项可能需要很多不同的方式,我得出结论来开发一个对象,以便它可以用于不同的场景和未来的项目
首先将这个类添加到你的项目中
public class SelectListDefaults { private IList<SelectListItem> getDefaultItems = new List<SelectListItem>(); public SelectListDefaults() { this.AddDefaultItem("(All)", "-1"); } public SelectListDefaults(string text, string value) { this.AddDefaultItem(text, value); } public IList<SelectListItem> GetDefaultItems { get { return getDefaultItems; } } public void AddDefaultItem(string text, string value) { getDefaultItems.Add(new SelectListItem() { Text = text, Value = value }); } }
现在在Controller Action中,你可以这样做
// Now you can do like this ViewBag.MainCategories = new SelectListDefaults().GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "-1")); // Or can change it by such a simple way ViewBag.MainCategories = new SelectListDefaults("Any","0").GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "0")); // And even can add more options SelectListDefaults listDefaults = new SelectListDefaults(); listDefaults.AddDefaultItme("(Top 5)", "-5"); // If Top 5 selected by user, you may need to do something here with db.MainCategories, or pass in parameter to method ViewBag.MainCategories = listDefaults.GetDefaultItems.Concat(new SelectList(db.MainCategories, "MainCategoryID", "Name", Request["DropDownListMainCategory"] ?? "-1"));
最后在View中你将会这样编码。
@Html.DropDownList("DropDownListMainCategory", (IEnumerable<SelectListItem>)ViewBag.MainCategories, new { @class = "form-control", onchange = "this.form.submit();" })
解决方法是使用@ tvanfosson的答案(选定的答案),并使用JQuery(或Javascript)将选项的值设置为0:
$(document).ready(function () { $('#DropDownListId option:first').val('0'); });
希望这可以帮助。
如果别人有更好的select,我不会
<% if (Model.VariableName == "" || Model.VariableName== null) { %> <%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], "", new{stlye=" "})%> <% } else{ %> <%= html.DropDpwnList("ListName", ((SelectList) ViewData["viewName"], Model.VariableName, new{stlye=" "})%> <% }>