關於mvc中@Html.DropDownListFor和@Html.DropDownList默認值無法選中問題簡單總結
結論:
無法綁定默認值是微軟MVC的一個BUG
觸發條件:
整個Controller中ViewBag或者ViewData構造的參數別名有與DropDownListFor和DropDownList構造的頁面標簽名字相同時出現。
注意是整個Controller中ViewBag和ViewData對象的所有參數,並不是賦值為SelectList的參數
例子:
錯誤:不能如願選中默認值
@Html.DropDownList("Filed1", ViewBag.Filed1 as SelectList, new { @class = "form-control" })
@Html.DropDownListFor(model=>model.Filed1, ViewBag.Filed1 as SelectList, new { @class = "form-control" })
正確:可以如願選中默認值
@Html.DropDownList("Filed1", ViewBag.temp as SelectList, new { @class = "form-control" })
@Html.DropDownListFor(model=>model.Filed1, ViewBag.temp as SelectList, new { @class = "form-control" })
結論:
參數命名很重要,因為看不到源碼,故猜測問題便是名稱問題。