繁体   English   中英

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

[英]Html.DropDownList in ASP.NET MVC RC (refresh) not pre-selecting item

在我的 controller 中,我有以下内容:

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

在我看来,我有:

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

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

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

如果您将 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( 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参数,而无效的方式传递false

在我看来,当usedViewDatafalse时,SelectInternal 内部某处可能存在错误。

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

以下对我有用(使用 MVC RC Refresh)

在视图中:

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

因此,对于您的示例,这可能是:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM