gpt4 book ai didi

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

转载 作者:太空狗 更新时间:2023-10-29 23:12:00 25 4
gpt4 key购买 nike

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

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

在我看来:

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

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

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

最佳答案

如果您将 ViewData 中的键名称与 View 中表单字段的名称相匹配,HtmlHelpers 将设计为基于该键从 ViewData 中隐式提取。我建议将您的 View 代码更改为:

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

HtmlHelpers 似乎在以这种方式使用它们时效果最好(尽管这并不总是可能的)。

更新:

为了进一步说明这似乎有效而其他方法无效的原因,我深入研究了 SelectExtensions.cs 的代码...

无论您如何调用 DropDownList,最终呈现实际 HTML 的是私有(private)方法 SelectInternal。 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

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

关于c# - ASP.NET MVC RC(刷新)中的 Html.DropDownList 未预选项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/589935/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com