Set selected item to SelectList collection

I have a class with the following property. It creates a SelectList object from an existing list and then sets the selected item.

 public SelectList ProviderTypeList { get { SelectList list = new SelectList([...my collection...], "Value", "Key"); SelectListItem item = list.FirstOrDefault(sli => sli.Text == SelectedProviderType); if (item != null) item.Selected = true; return list; } } 

However, when this code is finished, item.Selected will be true. But the corresponding item in the SelectList collection is still null.

I cannot find a way to update the object in the collection, so this parameter will be used in the resulting HTML.

I am using @Html.DropDownListFor to render HTML. But I see that the object inside the collection was not modified as soon as this code executed.

Can anyone see what I am missing?

+2
source share
2 answers

In SelectList

there is an optional additional parameter,
 SelectList list = new SelectList([...my collection...], "Value", "Key", SelectedID); 

Check definition

 public SelectList(IEnumerable items, string dataValueField, string dataTextField, object selectedValue); 

which sets the selected value and is of the same type as dataValueField

+8
source

Yes, these properties are read-only, the following code should work:

  SelectList selectList = new SelectList(Service.All, "Id", "Name"); foreach (SelectListItem item in selectList.Items) { if (item.Value == yourValue) { item.Selected = true; break; } } 
-1
source

Source: https://habr.com/ru/post/985964/


All Articles