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

13

118

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?

Urolith answered 21/3, 2009 at 2:7 Comment(2)
SelectList really seems to be just a helper for binding data directly to items. If you add items manually use List<SelectListItem> instead.Doscher
Given the accepted answer and number of votes, could I suggest you change the question slightly to reflect that answer i,e, "How can I add a blank-value item to a SelectList in ASP.net MVC"? But credit & thanks to @h-dog for answering the original "How can I add an item" per se questionAbstinence
T
156

There really isn't a need to do this unless you insist on the value of 0. The HtmlHelper DropDownList extension allows you to set an option label that shows up as the initial value in the select with a null value. Simply use one of the DropDownList signatures that has the option label.

<%= Html.DropDownList( "DropDownValue",
                       (IEnumerable<SelectListItem>)ViewData["Menu"],
                        "-- Select One --" ) %>
Travail answered 21/3, 2009 at 2:16 Comment(13)
What if you actually do insist on the value of 0? If the value is null/an empty string, it can cause problems with model binding.Waadt
If you are expecting it back as an int, then I would use int? and still leave it null if no selection has been made.Travail
The problem with this is solution is that you lose your selected item.Tsingyuan
I put html helper example belowStoddart
This does not work when using DropDownListFor, I had to use one of the solutions below.Thallic
@JesseWebb I suspect you just need to make sure you're using a signature that includes the option label, msdn.microsoft.com/en-us/library/ee703567.aspx, @Html.DropDownListFor( m => m.MenuSelection, (IEnumerable<SelectListItem>)ViewBag.Menu, "Select One", null ) for example, including the null htmlAttributes to avoid confusion with the signature that takes an expression, the menu enumeration, and an object (htmlAttributes).Travail
@Travail - Thank you for clarifying. I tried to use it with a Complex type as the type for the IEnumerable in the SelectList. I had to specify the dataValueField and the dataTestField which made this not work when adding an optionLabel value. It probably could have worked with a little more effort but I just used one of the alternative solutions. Thanks anyway though!Thallic
Also, a value is needed if you are using jquery.unobtrusive.js.Stratosphere
Apparently, I can't edit my previous post. So to be a little more specific, it's when DataAnnotationsModelValidatorProvider.AddImplicitRequiredAttributeForValueTypes is set to true. So there maybe an instance where you don't require a field, so you pass a value of 0 for the -- Select -- item.Stratosphere
Uncaught ReferenceError: Html is not definedSupererogatory
@MehmanBashirov this only works with MVC. If the Html property isn't defined on the ViewPage in MVC, you've got worse problems than trying to add an item to a select list. msdn.microsoft.com/en-us/library/…Travail
I insist on 0 so I can use binding. Passing null or no value is messy.Antimony
The same works for DropDownListFor: @Html.DropDownListFor(x => x.id, new SelectList(Model.LstItems, "value", "text"), "< NONE >", new { @class = "form-control" })Slake
R
88

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;
Renferd answered 29/4, 2010 at 0:23 Comment(1)
I recommend using the optionLabel overload in the HtmlHelper -> @Html.DropDownListForPerforce
B
23

This is possible.

//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);
Bowknot answered 5/6, 2013 at 15:20 Comment(2)
I recommend using the optionLabel overload in the HtmlHelper -> @Html.DropDownListForPerforce
If you're starting out with a SelectList that already has items in it, as in OP's case, the following line is also needed in order to preserve those items: newList.AddRange(myOriginalSelectList).Destructor
M
13

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);
}
Millionaire answered 1/6, 2015 at 20:31 Comment(1)
I recommend using the optionLabel overload in the HtmlHelper -> @Html.DropDownListForPerforce
S
5

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;
}
Stoddart answered 29/11, 2011 at 19:41 Comment(0)
R
5
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

Renick answered 6/2, 2012 at 10:16 Comment(2)
what if I have some selected values and I want to preserve them?Wilhelm
I recommend using the optionLabel overload in the HtmlHelper -> @Html.DropDownListForPerforce
W
4

The .ToList().Insert(..) method puts an element into your List. Any position can be specified. After ToList just add .Insert(0, "- - First Item - -")

Your code

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

New Code

SelectList list = new SelectList(repository.func.ToList().Insert(0, "- - First Item - -"));
Wappes answered 3/11, 2015 at 17:4 Comment(1)
SelectList.Items has no Add() method.Congruent
P
2

May not sound very elegant, but I usually do something like this:

    var items = repository.func.ToList();
    items.Insert(0, new funcItem { ID = 0, TextValue = "[None]" });
    ViewBag.MyData = new SelectList(items);
Polyphagia answered 3/9, 2012 at 4:0 Comment(0)
U
1

Okay I like clean code so I made this an extension method

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

Usage (by example):

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");
Uturn answered 21/8, 2012 at 23:37 Comment(0)
E
1

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();" })
Exceptive answered 15/1, 2015 at 21:39 Comment(0)
V
0

A work-around is to use @tvanfosson's answer (the selected answer) and use JQuery (or Javascript) to set the option's value to 0:

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

Hope this helps.

Viridissa answered 29/7, 2016 at 5:20 Comment(0)
T
0

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");
Thrasonical answered 18/4, 2019 at 18:40 Comment(0)
P
-5

I don't if anybody else has a better option...

<% 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=" "})%>
<% }>
Plasticity answered 19/1, 2010 at 19:10 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.