ValidateModel 数据注释问题
我有一个具有以下属性的 SearchViewModel:
[RegularExpression("name")]
public String SortField;
[RegularExpression("asc|desc")]
public String SortDirection;
如您所见,我希望“name”此时成为 SortField 的唯一有效值,“asc”或“desc”成为 SortDirection 的唯一有效值。
但是,当值不同时,ValidateModel 不会捕获任何错误,并且 ModelState.IsValid 返回 true。基本上我可以提供任何价值,并且它总是会通过。
缩写的控制器方法:
public ActionResult List(SearchViewModel model)
{
ValidateModel(model); // No error here
Boolean isValid = ModelState.IsValid // This is true
//...
}
我做错了什么?
编辑:我不确定这是否重要,但我正在使用自定义 ModelBinder。
I have a SearchViewModel with these properties:
[RegularExpression("name")]
public String SortField;
[RegularExpression("asc|desc")]
public String SortDirection;
As you can see, I want "name" to be the only valid value of SortField at this time, and "asc" or "desc" the only valid values for SortDirection.
However, ValidateModel isn't catching any error when the values are different, and ModelState.IsValid returns true. Basically I can supply any value and it will always go through.
The abbreviated controller method:
public ActionResult List(SearchViewModel model)
{
ValidateModel(model); // No error here
Boolean isValid = ModelState.IsValid // This is true
//...
}
What am I doing wrong?
Edit: I'm not sure if this is important, but I'm using a custom ModelBinder.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这些不是财产;而是财产。它们是领域。绑定和验证仅针对属性起作用。
仅供参考 -
[RegularExpression]
还允许用户不为输入指定任何值(将转换为 null)。如果您想要禁止空值,除了[RegularExpression]
之外,还可以使用[Required]
。Those aren't properties; they're fields. Binding and validation only work against properties.
FYI -
[RegularExpression]
also allows the user to specify no value for the input (which gets converted to a null). If you want to disallow null values, use[Required]
in addition to[RegularExpression]
.