DropDownListFor selectedItem 未按预期工作

DropDownListFor selectedItem not working as expected

我有一个简单的下拉菜单,它是用以下方式呈现的:

@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 呈现 select,这意味着值 = -1。

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

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

我相信以下link包含的示例代码应该能够对您有所帮助:

MVC DropDownList SelectedValue not displaying correctly

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

的值

SelectList 构造函数的第 4 个参数在绑定到 属性 时被忽略。唯一一次它被尊重是如果你要使用像 @Html.DropDownList("NotAPropertyOfMyModel, new (SelectList(...

这样的东西

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

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