asp.net-mvc 所选值不适用于 SelectList
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16604313/
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
Selected value not working for SelectList
提问by Pawan Nogariya
I found many questions and answers related to this issue but nothing worked for me
我发现了许多与此问题相关的问题和答案,但对我没有任何帮助
I am creating a dropdown list like this
我正在创建一个这样的下拉列表
@Html.DropDownListFor(m => m.SchoolYears, new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId), new { @class = "field_Dropdown", style = "width:100px;",onchange="return searchStudents();" })
(Model.CurrentYearIdis of type int)
(Model.CurrentYearId是类型int)
But it never lets current year selected.
但它永远不会让当前年份被选中。
From this post, I got that we should use string for selected value (although I don't know why because it allows object for selected value)
从这篇文章中,我知道我们应该对选定值使用字符串(虽然我不知道为什么,因为它允许对象作为选定值)
DropDownList SelectList SelectedValue issue
DropDownList SelectList SelectedValue 问题
so I tried all these variations
所以我尝试了所有这些变化
new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId.ToString())
new SelectList(Model.SchoolYears, "YearId", "StartDates", 2)
new SelectList(Model.SchoolYears, "YearId", "StartDates", "2")
But they even didn't work.
但他们甚至没有工作。
There is way to create the select list through linq query or foreach loop and mark selected property of each item but why the above doesn't work?
有办法通过 linq 查询或 foreach 循环创建选择列表并标记每个项目的选定属性,但为什么上述方法不起作用?
回答by Pawan Nogariya
Found the problem.
发现问题了。
The mistake I was doing is using this
我做的错误是使用这个
m => m.SchoolYears // m.SchoolYears in a list of string
When I changed it to this
当我把它改成这个
m => m.SelectedYearId // m.SelectedYearId is an integer property
it worked like a charm, so finally I have this working
它就像一个魅力,所以最后我有这个工作
@Html.DropDownListFor(m => m.SelectedYearId, new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId), new { @class = "field_Dropdown", style = "width:100px;",onchange="return searchStudents();" })
Thanks!
谢谢!
回答by irfandar
The solution did not work for me. It turns out selected property doesnot work if the ViewBag Property name and Model Property name is same so after changing the ViewBag Property name it worked.
该解决方案对我不起作用。事实证明,如果 ViewBag 属性名称和模型属性名称相同,则选定属性不起作用,因此在更改 ViewBag 属性名称后它起作用了。

