Home Selected property on SelectListItem not being set by SelectList constructor

# Selected property on SelectListItem not being set by SelectList constructor

KyleMit
1#
KyleMit Published in 2017-12-05 20:48:07Z
 I'm creating a SelectList to pass to a Html.DropDownList, but the correct value doesn't seem to be populating var x = new SelectList(new[] { new SelectListItem() { Value="1", Text="Vanilla"}, new SelectListItem() { Value="2", Text="Chocolate"}, new SelectListItem() { Value="3", Text="Strawberry"} }, "Value", "Text", "2");  SelectList should take a constructor that takes in the selectedValue: public SelectList( IEnumerable items, string dataValueField, string dataTextField, object selectedValue )  But this only sets the SelectedValue on the entire collection. The individual SelectListItems haven't been set as Selected Do I need to iterate over them individually and set selected for each as in this question?
Stephen Muecke
2#
Stephen Muecke Reply to 2017-12-05 23:03:15Z
 The Selected property is being set by the SelectList constructor. The image you have shown is for the items argument (i.e the collection of SelectListItem that you passing to the method), not the result of calling the method. The constructor does not modify the collection passed to it, it creates a new IEnumerable, and if you inspect the value of var x, then you will see that the 2nd SelectListItem (the one with Value = "2") will have its Selected property set to true. However, the purpose of the SelectListItem class is for use in one of the HtmlHelper methods that generates a `
 You need to login account before you can post.
Processed in 0.325695 second(s) , Gzip On .