代码之家  ›  专栏  ›  技术社区  ›  Iain Holder

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

  •  5
  • Iain Holder  · 技术社区  · 16 年前

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

    我认为:

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

    “渲染”下拉列表 应该 将Id为currentItem.Id的项目预先选中,但未选中。未选择任何内容,因此默认为第一个。

    这在我更新到RC/RC(刷新)之前就起作用了。有什么想法吗?

    3 回复  |  直到 15 年前
        1
  •  6
  •   Troy    16 年前

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

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

    HTMLHelper在以这种方式使用它们时似乎工作得最好(尽管这并不总是可能的)。

    更新:

    无论您如何调用DropDownList,私有方法SelectInternal最终都会呈现实际的HTML。SelectInternal的签名如下所示:

    SelectInternal( string optionLabel, string name, IEnumerable<SelectListItem> selectList, bool usedViewData, bool allowMultiple, IDictionary<string,object> htmlAttributes )
    

    以下是DropDownList的两种用法的路径:

    下拉列表(“myList”)

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

    下拉列表(“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 )
    

    因此,在一天结束时,这两条路径之间的区别在于,工作的方式是经过的 符合事实的 参数,而不起作用的方式经过 错误的 .

    usedViewData

        2
  •  0
  •   kay.herzam    16 年前

    以下内容适合我(使用MVC RC刷新)

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

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

    <%= Html.DropDownList("Id", (SelectList)ViewData["myList"]) %>
    
        3
  •  0
  •   oglester    15 年前

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