【问题标题】:DropDownListFor selectedItem not working as expectedDropDownListFor selectedItem 未按预期工作
【发布时间】:2015-08-20 14:17:21
【问题描述】:

我有一个简单的下拉列表,用:

@Html.DropDownListFor(m => m.Request.Value, new SelectList(items, "Value", "Text", selectedElement), new {})

其中Model.Request.Value 的类型为int,其值设置为-1。 items 是这样构建的:

var items = new List<SelectListItem<int>>();

items.Add(new SelectListItem<int>{Text = "10", Value = 10});
items.Add(new SelectListItem<int>{Text = "25", Value = 25});
items.Add(new SelectListItem<int>{Text = "100", Value = 100});
items.Add(new SelectListItem<int>{Text = "All", Value = -1});

selectedElement 的值为 25,属于int 类型。但是,它总是使用 All selected 呈现选择,这意味着 value = -1。

为什么?为什么会有一个值 selectedElement 无论如何都会被覆盖?

【问题讨论】:

    标签: c# asp.net-mvc-4 razor html.dropdownlistfor


    【解决方案1】:

    您对模型中的属性的强绑定,因此它的属性值决定了选择的内容。这就是模型绑定的工作原理。如果要选择"All",请设置Request.Value = -1的值

    SelectList 构造函数的第四个参数在绑定到属性时被忽略。唯一受到尊重的情况是,如果您使用 @Html.DropDownList("NotAPropertyOfMyModel, new (SelectList(...

    之类的东西

    旁注:itemsIEnumerable&lt;SelectListItem&gt;(这是 DropDownListFor() 方法所需要的)所以创建一个新的 IEnumerable&lt;SelectListItem&gt;(这是 SelectList 是)只是毫无意义的额外开销。你的观点应该只是

    @Html.DropDownListFor(m => m.Request.Value, items)
    

    【讨论】:

      【解决方案2】:

      DropDownListFor 使用 lambda 表达式的值来选择下拉列表中的项目,而不是 SelectList 构造函数的最后一个参数。

      我相信以下链接包含的示例代码应该可以帮助到您:

      MVC DropDownList SelectedValue not displaying correctly

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-10-14
        • 2021-06-04
        • 2022-01-24
        • 2015-05-11
        • 2020-05-15
        • 2014-10-31
        • 2018-02-12
        • 2014-01-20
        相关资源
        最近更新 更多