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: *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.
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 SelectListItem
s 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" });