C# IEnumerable<string> 到 SelectList,没有值被选中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/222531/
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
IEnumerable<string> to SelectList, no value is selected
提问by Chris Canal
I have something like the following in an ASP.NET MVC application:
我在 ASP.NET MVC 应用程序中有类似以下内容:
IEnumerable<string> list = GetTheValues();
var selectList = new SelectList(list, "SelectedValue");
And even thought the selected value is defined, it is not being selected on the view. I have this feeling I'm missing something here, so if anyone can put me out my misery!
即使认为选定的值已定义,它也没有在视图上被选中。我有这种感觉,我在这里错过了一些东西,所以如果有人可以让我摆脱痛苦!
I know I can use an annoymous type to supply the key and value, but I would rather not add the additional code if I didn't have to.
我知道我可以使用 annoymous 类型来提供键和值,但如果我不需要,我宁愿不添加额外的代码。
EDIT: This problem has been fixed by ASP.NET MVC RTM.
编辑:此问题已由 ASP.NET MVC RTM 修复。
回答by Tim Scott
Try this instead:
试试这个:
IDictionary<string,string> list = GetTheValues();
var selectList = new SelectList(list, "Key", "Value", "SelectedValue");
SelectList (at least in Preview 5) is not clever enough to see that elements of IEnumerable are value type and so it should use the item for both value and text. Instead it sets the value of each item to "null" or something like that. That's why the selected value has no effect.
SelectList(至少在预览版 5 中)不够聪明,无法看到 IEnumerable 的元素是值类型,因此它应该对值和文本都使用该项目。相反,它将每个项目的值设置为“null”或类似的值。这就是所选值无效的原因。
回答by KP.
Take a look at this: ASP.NET MVC SelectList selectedValue Gotcha
看看这个:ASP.NET MVC SelectList selectedValue Gotcha
This is as good explanation of what is going on as any.
这是对正在发生的事情的很好的解释。
回答by Alex
If you're just trying to to map an IEnumerable<string>
to SelectList
you can do it inline like this:
如果您只是想将 an 映射IEnumerable<string>
到SelectList
您可以像这样内联:
new SelectList(MyIEnumerablesStrings.Select(x=>new KeyValuePair<string,string>(x,x)), "Key", "Value");
回答by Jay Sheth
Try this
尝试这个
ViewBag.Items = list.Select(x => new SelectListItem()
{
Text = x.ToString()
});