When I create a SelecList, I want to be able to add SelecListItem manually, and for 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 creating the SelectList, I pass it to DropDownListFor via the ViewBag:
Html.DropDownListFor(m => m.StartPointProvince, (SelectList)ViewBag.Provinces)
However, when I create a SelectList using the first method, it does not work. It adds 3 values ββto the drop-down list, but all values ββare displayed as:
* Screenshot with exit
However, when I use the second method, it works fine. I want to use the first method, because I want to be able to specify the text and value for each element.
source share