Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

People also ask

How to add values to SelectList in c#?

Add(new SelectListItem { Text = "PQR", Value = "PQR" }); objCIFFOB. Add(new SelectListItem { Text = "XYZ", Value = "XYZ" }); ViewBag.

How to add List items to dropdownlist in MVC?

You should create it in the controller and pass it using the ViewData. Example: var list = new SelectList(new [] { new {ID="1",Name="name1"}, new{ID="2",Name="name2"}, new{ID="3",Name="name3"}, }, "ID","Name",1); ViewData["list"]=list; return View();


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

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;

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

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