c# - Adding SelectListItem manually to SelectList to use in DropDownListFor -
when create seleclist wish able add seleclistitem's manually , use 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 :
var lstprovinces = new selectlist(new[] { "northern cape", "free state", "western cape" });
after created selectlist, pass dropdownlistfor via viewbag :
html.dropdownlistfor(m => m.startpointprovince, (selectlist)viewbag.provinces)
however when create selectlist using first method, doesn't work - adds 3 values dropdown list, values display as: *screenshot of output
however when use second method, works fine. wish use first method because want able specify text , value of each item.
the problem selectlist(ienumerable)
constructor doesn't accept selectlistitem
's (at least not selectlistitem
add items
collection). accepts collection of arbitrary objects used generate unrelated internal selectlistitem
s collection.
if want, 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 work. unnecessary, because create complex selectlistitem
items won't used selectlist
- treat them other data object.
in same way can use 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" });
Comments
Post a Comment