在SelectList集合中设置所选项目 [英] Set Selected Item in SelectList Collection
问题描述
我有一个具有以下属性的类.它从现有列表中构造一个 SelectList
对象,然后设置所选项目.
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;
}
}
但是,此代码完成后, item.Selected
为true.但是 SelectList
集合中的对应项目仍然为空.
However, when this code is finished, item.Selected
is true. But the corresponding item in the SelectList
collection is still null.
我似乎找不到一种方法来更新集合中的对象,因此该设置将用于结果HTML中.
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.
我正在使用 @ Html.DropDownListFor
呈现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?
推荐答案
SelectList
SelectList list = new SelectList([...my collection...], "Value", "Key", SelectedID);
检查定义
public SelectList(IEnumerable items, string dataValueField, string dataTextField,
object selectedValue);
设置所选值,并且与 dataValueField
这篇关于在SelectList集合中设置所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!