Set Selected Item in SelectList Collection

喜夏-厌秋 提交于 2019-12-12 15:19:26

问题


I have a class with the following property. It constructs 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 is true. But the corresponding item in the SelectList collection is still null.

I can't seem to find a way to update the object in the collection, so that the setting will be used in the resulting HTML.

I'm using @Html.DropDownListFor to render the HTML. But I can see that the object within the collection was not modified as soon as this code has executed.

Can anyone see what I'm missing?


回答1:


There is an optional additional parameter in SelectList

SelectList list = new SelectList([...my collection...], "Value", "Key", SelectedID);

Check the definition

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

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




回答2:


I have a list of items called id_waers.

var id_waers = db.MONEDAs.Where(m => m.ACTIVO == true).ToList();

where the id is "WAERS".

I will create a SelectList with id_waers values, "WAERS" as id and the text to show will be the id too and show the "USD" value as selected

ViewBag.MONEDA = new SelectList(id_waers, "WAERS", dataTextField: "WAERS", selectedValue: "USD");

default value

I have another options




回答3:


Yes this properties are read only, 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;
            }
        }


来源:https://stackoverflow.com/questions/16598512/set-selected-item-in-selectlist-collection

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!