如何将项添加到ASP.net MVC中的SelectList

时间:2009-03-21 02:07:17

标签: asp.net-mvc selectlist

基本上我想在SelectList的开头插入一个项目,默认值为0,文本值为“ - 选择一个 - ”

这样的东西
SelectList list = new SelectList(repository.func.ToList());
ListItem li = new ListItem(value, value);
list.items.add(li);

可以这样做吗?

13 个答案:

答案 0 :(得分:145)

除非你坚持使用值0,否则确实没有必要这样做.HtmlHelper DropDownList扩展允许你设置一个选项标签,它在select值中显示为初始值,带有空值。只需使用具有选项标签的DropDownList签名之一。

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

答案 1 :(得分:77)

我通过填充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;

答案 2 :(得分:15)

这是可能的。

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

答案 3 :(得分:13)

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

答案 4 :(得分:4)

这里有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;
}

答案 5 :(得分:4)

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

这应该做你需要的,只需发送你的选择列表,它将返回一个带有索引0中项目的选择列表

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

答案 6 :(得分:3)

.ToList()。Insert(..)方法将一个元素放入List中。可以指定任何位置。 ToList之后只需添加 .Insert(0,&#34; - - First Item - - &#34;)

您的代码

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

答案 7 :(得分:2)

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

    var items = repository.func.ToList();
    items.Insert(0, new funcItem { ID = 0, TextValue = "[None]" });
    ViewBag.MyData = new SelectList(items);

答案 8 :(得分:1)

好的,我喜欢干净的代码,所以我把它作为扩展方法

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

答案 9 :(得分:1)

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

首先将此类添加到项目中

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

答案 10 :(得分:0)

解决方法是使用@ tvanfosson的答案(选定的答案)并使用JQuery(或Javascript)将选项的值设置为0:

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

希望这有帮助。

答案 11 :(得分:0)

尝试类似以下代码的内容:

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

答案 12 :(得分:-5)

如果其他人有更好的选择,我不会......

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