如果将ViewData中的键名与视图中表单字段的名称匹配,HtmlHelpers会根据该键名隐式地从ViewData中提取数据。建议您将视图代码更改为:
<%= Html.DropDownList("myList") %>
HtmlHelpers似乎在以下方式下最有效(尽管这并非总是可能的)。
更新:
为了进一步阐述为什么这种方法似乎有效而其他方法不行,我深入研究了SelectExtensions.cs的代码...
无论如何调用DropDownList,私有方法SelectInternal最终呈现实际的HTML。SelectInternal的签名如下:
SelectInternal( string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool usedViewData, bool allowMultiple, IDictionary<string,object> htmlAttributes )
以下是两种DropDownList使用的路径:
DropDownList("myList")
(注:本文中保留了HTML标签)
DropDownList( string name ) ->
SelectInternal( null, name, htmlHelper.GetSelectData(name), true, false, null )
DropDownList("myItem",(SelectList)ViewData["myList"])
下拉列表
该代码是一个下拉列表,其中“myItem”是下拉列表的名称,“myList”是选择列表的数据源。
List( string name, IEnumerable<SelectListItem> selectList ) ->
DropDownList( name, selectList, null ) ->
DropDownList( name, selectList, new RouteValueDictionary(htmlAttributes) ) ->
SelectInternal( null, name, selectList, false, false, htmlAttributes )
所以说,最终的区别在于,有效的方法将 true 传递到 SelectInternal 的 usedViewData 参数中,而无效的方法则传递 false。
我认为当 usedViewData 为 false 时,SelectInternal 内部可能存在 bug。