简体   繁体   English

Razor中的Enum下拉值必需错误

[英]Enum Dropdown value required error in Razor

Is there any way to make an enum's dropdownlist optional? 有什么办法可以使枚举的下拉列表成为可选的? When the form posts with no value for this dropdown, ModelState.IsValid evaluates to false with an error that a value is required for this dropdown. 当表单发布的该下拉列表没有任何值时, ModelState.IsValid计算结果为false ,错误提示此下拉列表需要一个值。 I have not explicitly used [Required] attribute on this property. 我尚未在此属性上显式使用[Required]属性。

@Html.EnumDropDownListFor(m => m.People[0].Role, "Select a role", new { @class = "form-control role" })

The enum is: 枚举是:

public enum RoleType { Employee, Visitor, Vendor, Witness }

Is the property m.People[0].Role nullable in your model. 属性m.People [0] .Role在模型中是否可以为空。 You can set the RoleType to be nullable and this should remove the validation error. 您可以将RoleType设置为可为空,这将消除验证错误。

public RoleType? Role {get;set;}

It appears that there is a way that you can remove specific properties from the ModelState by using something like 看来,有一种方法可以使用类似以下的方法从ModelState中删除特定属性:

ModelState.Remove("nameOfProperty");

This info was found on another Stackoverflow post at the following link 此信息是在以下链接的另一个Stackoverflow帖子上找到的

ModelState.IsValid does not exclude required property ModelState.IsValid不排除必需的属性

Not sure if this relates directly to your issue, but hope this helps. 不知道这是否直接关系到您的问题,但希望对您有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM