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

2020-01-27 12:55发布

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?

13条回答
叛逆
2楼-- · 2020-01-27 13:02

Try something like the following code:

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");
查看更多
趁早两清
3楼-- · 2020-01-27 13:03

I got this to work by Populating a SelectListItem, converting to an List, and adding a value at index 0.

List<SelectListItem> items = new SelectList(CurrentViewSetups, "SetupId", "SetupName", setupid).ToList(); 
items.Insert(0, (new SelectListItem { Text = "[None]", Value = "0" }));
ViewData["SetupsSelectList"] = items;
查看更多
SAY GOODBYE
4楼-- · 2020-01-27 13:03

As this option may need in many different manners, i reached to conclusion to develop an object so that it can be used in different scenarios and in future projects

first add this class to your project

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

Now in Controller Action you can do like this

    // 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();" })
查看更多
The star\"
5楼-- · 2020-01-27 13:14

I liked @AshOoO's answer but like @Rajan Rawal I needed to preserve selected item state, if any. So I added my customization to his method 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);
}
查看更多
我欲成王,谁敢阻挡
6楼-- · 2020-01-27 13:14
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

You can custome the text,value or even the index of the item you need to insert

查看更多
爱情/是我丢掉的垃圾
7楼-- · 2020-01-27 13:15

Here html helper for you

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;
}
查看更多
登录 后发表回答