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

时间:2009-02-26 10:16:28

标签: c# .net asp.net-mvc

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

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

我认为:

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

呈现的下拉列表 应该预先选择id为currentItem.Id的项目,但事实并非如此。没有选择任何内容,因此它默认为第一个。

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

3 个答案:

答案 0 :(得分:6)

如果您将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)计算机[ “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 work传递 false

usedViewData false 时,我觉得SelectInternal里面有一个错误。

答案 1 :(得分:0)

以下适用于我(使用MVC RC刷新)

在视图中:

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

所以你的例子可能是:

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

答案 2 :(得分:0)

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