Adding SelectListItem manually to SelectList to use in DropDownListFor

Marnus Steyn picture Marnus Steyn · Apr 25, 2015 · Viewed 89.4k times · Source

When I create a SelecList I wish to be able to add SelecListItem's manually and to do this I use this code:

List<SelectListItem> Provinces = new List<SelectListItem>();
Provinces.Add(new SelectListItem() { Text = "Northern Cape", Value = "NC" });
Provinces.Add(new SelectListItem() { Text = "Free State", Value = "FS" });
Provinces.Add(new SelectListItem() { Text = "Western Cape", Value = "WC" });

SelectList lstProvinces = new SelectList(Provinces);

Instead of this :

var lstProvinces = new SelectList(new[] { "Northern Cape", "Free State", "Western Cape" });

After I created the SelectList, I pass it to the DropDownListFor via the ViewBag :

Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces)

However when I create the SelectList using the first method, it doesn't work - It adds the 3 values to the dropdown list, but all the values display as: Code *screenshot of output

However when I use the second method, it works fine. I wish to use the first method because i want to be able to specify the Text AND value of each item.

Answer

Eugene Podskal picture Eugene Podskal · Apr 25, 2015

The problem is that SelectList(IEnumerable) constructor doesn't accept SelectListItem's (at least not as SelectListItem to add to its Items collection). It simply accepts collection of some arbitrary objects that will be used to generate completely unrelated internal SelectListItems collection.

If you want, you can use SelectList(IEnumerable, string, string) constructor in such way:

List<SelectListItem> Provinces = new List<SelectListItem>();
Provinces.Add(new SelectListItem() { Text = "Northern Cape", Value = "NC" });
Provinces.Add(new SelectListItem() { Text = "Free State", Value = "FS" });
Provinces.Add(new SelectListItem() { Text = "Western Cape", Value = "WC" });

this.ViewBag.Provinces = new SelectList(Provinces, "Value", "Text");

It will work. But it is unnecessary, because you create complex SelectListItem items that won't be used by the SelectList - it will just treat them as any other data object.

In the same way you can just use some other simpler class in place of SelectListItem:

public class SelectListModel
{
    public String Text { get; set; }
    public String Value { get; set; }
}

...
Provinces.Add(new SelectListModel() { Text = "Northern Cape", Value = "NC" });