How can I add an item to a SelectList in ASP.net MVC

Basically I am looking to insert an item at the beginning of a SelectList with the default value of 0 and the Text Value of " -- Select One --"

Something like

SelectList list = new SelectList(repository.func.ToList());
ListItem li = new ListItem(value, value);
list.items.add(li);

Can this be done?

203955 次浏览

实际上没有必要这样做,除非您坚持要求值为0。HtmlHelper DropDownList 扩展允许您设置一个选项标签,该标签在选择中显示为初始值,值为空。只需使用带有选项标签的 DropDownList 签名之一。

<%= Html.DropDownList( "DropDownValue",
(IEnumerable<SelectListItem>)ViewData["Menu"],
"-- Select One --" ) %>

我不知道别人有没有更好的选择。

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

我通过填充 SelectListItem、转换为 List 并在索引0处添加一个值来实现这一点。

List<SelectListItem> items = new SelectList(CurrentViewSetups, "SetupId", "SetupName", setupid).ToList();
items.Insert(0, (new SelectListItem { Text = "[None]", Value = "0" }));
ViewData["SetupsSelectList"] = items;

这里为您提供 html 帮助

public static SelectList IndividualNamesOrAll(this SelectList Object)
{
MedicalVarianceViewsDataContext LinqCtx = new MedicalVarianceViewsDataContext();


//not correct need individual view!
var IndividualsListBoxRaw =  ( from x in LinqCtx.ViewIndividualsNames
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;
}
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");
}

This Should do what you need ,just send your selectlist and it will return a select list with an item in index 0

您可以自定义需要插入的项的文本、值甚至索引

好的,我喜欢干净的代码,所以我把它做成了一个扩展方法

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

可能听起来不是很优雅,但我通常会这样做:

    var items = repository.func.ToList();
items.Insert(0, new funcItem { ID = 0, TextValue = "[None]" });
ViewBag.MyData = new SelectList(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);

由于这个选项可能需要在许多不同的方式,我得出的结论是开发一个对象,以便它可以在不同的场景和未来的项目中使用

首先将此类添加到项目中

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

And finally in View you will code like this.

@Html.DropDownList("DropDownListMainCategory", (IEnumerable<SelectListItem>)ViewBag.MainCategories, new { @class = "form-control", onchange = "this.form.submit();" })

我喜欢@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);
}

The 。 ToList ()。插入(. .) method puts an element into your List. Any position can be specified. After ToList just add 。插入(0,“-- 第一项-”)

你的密码

SelectList list = new SelectList(repository.func.ToList());

New Code

SelectList list = new SelectList(repository.func.ToList().Insert(0, "- - First Item - -"));

一个解决方案是使用@tvanfoson 的答案(选中的答案) ,并使用 JQuery (或 Javascript)将选项的值设置为0:

$(document).ready(function () {
$('#DropDownListId option:first').val('0');
});

Hope this helps.

试试下面的代码:

MyDAO MyDAO = new MyDAO();
List<MyViewModel> _MyDefault = new List<MyViewModel>() {
new MyViewModel{
Prop1= "All",
Prop2 = "Select all"
}
};
ViewBag.MyViewBag=
new SelectList(MyDAO
.MyList().Union(
_MyDefault
), "Prop1", "Prop2");