C# 设置 SelectList 集合中的选定项
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16598512/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Set Selected Item in SelectList Collection
提问by Jonathan Wood
I have a class with the following property. It constructs a SelectListobject from an existing list, and then sets the selected item.
我有一个具有以下属性的类。它SelectList从现有列表构造一个对象,然后设置所选项目。
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.Selectedis true. But the corresponding item in the SelectListcollection is still null.
然而,当这段代码完成后,item.Selected是真的。但是SelectList集合中对应的项仍然为空。
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 中使用该设置。
I'm using @Html.DropDownListForto render the HTML. But I can see that the object within the collection was not modified as soon as this code has executed.
我正在使用@Html.DropDownListFor来呈现 HTML。但是我可以看到,只要执行此代码,集合中的对象就没有被修改。
Can anyone see what I'm missing?
谁能看到我错过了什么?
采纳答案by Peter Smith
There is an optional additional parameter in SelectList
有一个可选的附加参数 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
它设置选定的值并且与 dataValueField
回答by Khurshid
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;
}
}
回答by Matías Gallegos
I have a list of items called id_waers.
我有一个名为 id_waers 的项目列表。
var id_waers = db.MONEDAs.Where(m => m.ACTIVO == true).ToList();
where the id is "WAERS".
其中 id 是“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
我将创建一个带有 id_waers 值的 SelectList,“WAERS”作为 id,要显示的文本也将是 id 并显示“USD”值作为选择
ViewBag.MONEDA = new SelectList(id_waers, "WAERS", dataTextField: "WAERS", selectedValue: "USD");

