重用模型属性作为SelectList项的来源会导致在一个选择控件中选择错误的选项

本文关键字:选择 一个 选项 错误 控件 属性 模型 SelectList | 更新日期: 2023-09-27 18:13:46

在我的模型中,我已经为AvailableOptions声明了属性,以及一些其他3个属性,用于3个不同的选项,具有相同的值范围:

public IEnumerable<SelectListItem> AvailableOptions{ get; set; }
public SomeCustomEnum? OptionNumberOne{ get; set; }
public SomeCustomEnum? OptionNumberTwo{ get; set; }
public SomeCustomEnum? OptionNumberThree{ get; set; }

我只在应用程序的一个地方填充它,模型构建器,基于一些enum值的SelectListItems集合。

然后,我在视图的3个不同的地方为3个不同的控件使用它:

@Html.DropDownListFor(m => m.OptionNumberOne, Model.AvailableOptions, "Choose...")
@Html.DropDownListFor(m => m.OptionNumberTwo, Model.AvailableOptions, "Choose...")
@Html.DropDownListFor(m => m.OptionNumberThree, Model.AvailableOptions, "Choose...")

当我将模型生成器中的模型属性值设置为

OptionNumberOne = null;
OptionNumberTwo = SomeCustomEnum.Value1;
OptionNumberThree = null;

我得到3选择下拉控件预选值,但不是预期的默认选择值

"Choose..."
"Value1"
"Choose..."

I got

"Choose..."
"Value1"
"Value1"

我在这里错过了什么?如果我向这些选项添加不同的值(不是null),它们将以正确的选择值呈现。此外,似乎添加另一个AvailableOptions属性(AvailableOptions2)并将其绑定到第三个下拉修复了这种情况,但我不想这样做。什么好主意吗?

重用模型属性作为SelectList项的来源会导致在一个选择控件中选择错误的选项

在返回视图之前使用ModelState.Clear()语句

你可以试试

@Html.DropDownListFor(m => m.OptionNumberOne, new SelectList(Model.AvailableOptions,"Value",
   "Text"), "Choose...")
@Html.DropDownListFor(m => m.OptionNumberTwo,new SelectList(Model.AvailableOptions,"Value",
   "Text"), "Choose...")
@Html.DropDownListFor(m => m.OptionNumberThree,new SelectList(Model.AvailableOptions,"Value",
   "Text"), "Choose...")