Asp.net-Mvc
所選值不適用於 SelectList
我發現了許多與此問題相關的問題和答案,但對我沒有任何幫助
我正在創建一個這樣的下拉列表
@Html.DropDownListFor(m => m.SchoolYears, new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId), new { @class = "field_Dropdown", style = "width:100px;",onchange="return searchStudents();" })(
Model.CurrentYearId是類型int)但它永遠不會讓目前年份被選中。
從這篇文章中,我知道我們應該使用字元串作為選定值(雖然我不知道為什麼,因為它允許對像作為選定值)
DropDownList SelectList SelectedValue 問題
所以我嘗試了所有這些變化
new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId.ToString()) new SelectList(Model.SchoolYears, "YearId", "StartDates", 2) new SelectList(Model.SchoolYears, "YearId", "StartDates", "2")但他們甚至沒有工作。
有辦法通過 linq 查詢或 foreach 循環創建選擇列表並標記每個項目的選定屬性,但為什麼上述方法不起作用?
發現了問題。
我正在做的錯誤是使用這個
m => m.SchoolYears // m.SchoolYears in a list of string當我把它改成這個
m => m.SelectedYearId // m.SelectedYearId is an integer property它就像一個魅力,所以最後我有這個工作
@Html.DropDownListFor(m => m.SelectedYearId, new SelectList(Model.SchoolYears, "YearId", "StartDates", Model.CurrentYearId), new { @class = "field_Dropdown", style = "width:100px;",onchange="return searchStudents();" })謝謝!
該解決方案對我不起作用。事實證明,如果 ViewBag 屬性名稱和模型屬性名稱相同,則選定的屬性不起作用,因此在更改 ViewBag 屬性名稱後它起作用了。