ASP.NET MVC RC中的Html.DropDownList(刷新)不预先选择项目

在我的控制器中,我有以下内容:

ViewData["myList"] = new SelectList(itemRepository.GetAll(), "Id", "Name", currentItem.Id); 

在我看来,我有:

  

渲染的下拉列表应该具有预先选择的Id为currentItem.Id的项目,但它没有。 没有选择任何内容,因此它默认为第一个。

这在我更新到RC / RC(刷新)之前有效。 有任何想法吗?

如果将ViewData中键的名称与视图上表单域的名称相匹配,则HtmlHelpers旨在根据该键隐式从ViewData中提取。 我建议将您的视图代码更改为:

 <%= Html.DropDownList("myList") %> 

HtmlHelpers在以这种方式使用时似乎效果最好(尽管并非总是可行)。

更新:

为了扩展这个似乎工作的原因,而其他方法没有,我深入研究SelectExtensions.cs的代码……

但是,您调用DropDownList,私有方法SelectInternal最终呈现实际的HTML。 SelectInternal的签名如下:

 SelectInternal( string optionLabel, string name, IEnumerable selectList, bool usedViewData, bool allowMultiple, IDictionary htmlAttributes ) 

这是DropDownList的两个用法所采用的路径:

DropDownList的( “myList中”)

 DropDownList( string name ) -> SelectInternal( null, name, htmlHelper.GetSelectData(name), true, false, null ) 

DropDownList(“myItem”,(SelectList)ViewData [“myList”]) DropDown

 List( string name, IEnumerable selectList ) -> DropDownList( name, selectList, null /* object, htmlAttributes */ ) -> DropDownList( name, selectList, new RouteValueDictionary(htmlAttributes) ) -> SelectInternal( null, name, selectList, false, false, htmlAttributes ) 

因此,在一天结束时,两条路径之间的区别在于,工作方式将true传递给SelectInternal的usedViewData参数,而不起作用的方式传递false

usedViewDatafalse时,我觉得SelectInternal里面有一个bug。

以下适用于我(使用MVC RC Refresh)

在视图中:

 <%= Html.DropDownList("NAME_OF_ITEM_ID_PROPERTY", (SelectList)ViewData["myList"]) %> 

所以对于你的例子可能是:

 <%= Html.DropDownList("Id", (SelectList)ViewData["myList"]) %> 

我只是制作了自己的下拉助手。 也许不如内置的那么高效,但确实有效。