IEnumerable <string>到SelectList,没有选择任何值

Chr*_*nal 15 c# asp.net-mvc

我在ASP.NET MVC应用程序中有类似的内容:

IEnumerable<string> list = GetTheValues();
var selectList = new SelectList(list, "SelectedValue");
Run Code Online (Sandbox Code Playgroud)

甚至认为选定的值已定义,它在视图中未被选中.我有这种感觉,我在这里错过了一些东西,所以如果有人能把我的痛苦赶出去!

我知道我可以使用烦人的类型来提供密钥和值,但如果我不需要,我宁愿不添加额外的代码.

编辑:ASP.NET MVC RTM已修复此问题.

Tim*_*ott 14

试试这个:

IDictionary<string,string> list = GetTheValues();
var selectList = new SelectList(list, "Key", "Value", "SelectedValue");
Run Code Online (Sandbox Code Playgroud)

SelectList(至少在预览版5中)不够聪明,看不到IEnumerable的元素是值类型,因此它应该将值用于值和文本.相反,它将每个项目的值设置为"null"或类似的东西.这就是所选值无效的原因.


Ale*_*lex 14

如果您只是想将地图映射IEnumerable<string>SelectList您,可以像这样内联:

new SelectList(MyIEnumerablesStrings.Select(x=>new KeyValuePair<string,string>(x,x)), "Key", "Value");
Run Code Online (Sandbox Code Playgroud)

  • 而不是.Select(...),你可以.ToDictionary(...) (3认同)