gpt4 book ai didi

c# - 为什么 EnumDropDownListFor 在 url 参数与模型中的字段相同时绑定(bind)不正确

转载 作者:行者123 更新时间:2023-11-30 16:52:52 25 4
gpt4 key购买 nike

我有一个页面包含一个枚举的下拉列表,它绑定(bind)到模型中的一个字段上,我还有一个具有相同名称的 url 参数(首字母的大小写不同)。

当 url 参数为空时,枚举的绑定(bind)不正确。为了澄清我的问题,请参阅下面的详细代码。

例如,当 url 为 Index?eventType= 时, View 最初显示 Type1 而不是 Type2。 MVC5 是否有任何特殊规则导致这种奇怪的行为?

当我更改模型中的 url 参数名称或字段名称时,下拉列表可以在加载时选择 Type2 Index?eventType=

查看:

@model TestMode
@{
Layout = null;
}

@Html.EnumDropDownListFor(m => m.EventType)

Controller :

    public ActionResult Index(int? eventType)
{
var viewModel = new TestMode();
viewModel.EventType = eventType.HasValue ?
(CalendarEventType)eventType.Value :
CalendarEventType.Type2;
//Check the value of EventType here is CalendarEventType.Type2, but when the view loaded, there are not selected for the drop down list of enum
return View(viewModel);
}

View 模型:

public class TestMode
{
public CalendarEventType EventType { get;set;}
}

public enum CalendarEventType
{
Type1 = 0,
Type2 = 1,
}

Index?eventType= 的 HTML,没有选项可以选择。

<select data-val="true" data-val-required="EventType field is required" id="EventType" name="EventType">
<option value="0">Type1</option>
<option value="1">Type2</option>
</select>

最佳答案

这是默认行为。您的参数名为 eventType,因此在调用该方法时,eventType 的值将添加到 ModelState(将为 null) 通过 DefaultModelBinder

当你使用 html 助手时,在你的例子中 EnumDropDownListFor(),他们使用来自 ModelState 的值(如果它们存在)而不是你的属性的实际值,所以帮助程序有效地使用值 null,而不是 Type2 来进行绑定(bind)。因为 null 与其中一个枚举值不匹配,所以选择了第一个值 (Type1)(因为必须选择某些值)。

此行为的原因在 this answer 的第二部分中进行了解释.

最简单的解决方案是更改参数的名称,使其与您的某个属性的名称不匹配(注意 DefaultModelBinder 不区分大小写,因此 eventTypeEventType 实际上是相同的)。另一种方法是在初始化 TestMode 对象之前添加 ModelState.Clear()

关于c# - 为什么 EnumDropDownListFor 在 url 参数与模型中的字段相同时绑定(bind)不正确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32025397/

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