基本上我想在SelectList的开头插入一个项目,默认值为0,文本值为" - 选择一个 - "
就像是
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)ViewData["Menu"], "-- Select One --" ) %>
我通过填充SelectListItem,转换为List,并在索引0处添加值来实现此功能.
Listitems = 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 ListnewList = new List (); //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) { ListnewList = 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); }
这里的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 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;
}