Adding SelectListItem manually to SelectList to use in DropDownListFor
Use DropDownList and name it the same as the model's property name. Mine is "ItemType"
@Html.LabelFor(model => model.ItemType, new { @class = "control-label" })
@Html.DropDownList("ItemType", (IEnumerable<SelectListItem>)ViewBag.ItemTypes, new { @class = "form-control" })
@Html.ValidationMessageFor(model => model.ItemType, null, new { @class = "text-danger" })
var types = new List<SelectListItem>();
types.Add(new SelectListItem() { Text = "Select...", Value = string.Empty });
types.Add(new SelectListItem() { Text = "OTC", Value = "0" });
types.Add(new SelectListItem() { Text = "Generic", Value = "1" });
types.Add(new SelectListItem() { Text = "Brand", Value = "2" });
types.Add(new SelectListItem() { Text = "Non-Merchandise", Value = "9" });
ViewBag.ItemTypes = types;
[Required(ErrorMessage = "Item Type is required")]
public Int32 ItemType { get; set; }
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" });