如果您将 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")
DropDownList( string name ) ->
SelectInternal( null, name, htmlHelper.GetSelectData(name), true, false, null )
DropDownList("myItem",(SelectList)ViewData["myList"])
下拉
List( string name, IEnumerable<SelectListItem> selectList ) ->
DropDownList( name, selectList, null /* object, htmlAttributes */ ) ->
DropDownList( name, selectList, new RouteValueDictionary(htmlAttributes) ) ->
SelectInternal( null, name, selectList, false, false, htmlAttributes )
因此,归根结底,这两种路径之间的区别在于,有效的方式将 true 传递给 SelectInternal 的 usedViewData 参数,而无效的方式' t 工作通过 false.
在我看来,当 usedViewData 为 false 时,SelectInternal 内部某处可能存在错误。