问题描述
我有多个布尔属性视图模型,在我的控制器我已经检查 ModelState.IsValid
在进行服务层之前。现在我要作出这样的 ModelState.IsValid
收益假
如果没有布尔属性设置为true的,有什么办法要做到这一点?
下面是我的示例类
公开类角色{
公众诠释标识{搞定;设置;}
[必需(的ErrorMessage =请输入角色名称)]
公共字符串名称{;设置;}
公共BOOL IsCreator {搞定;设置;}
公共BOOL IsEditor {搞定;设置;}
公共BOOL IsPublisher {搞定;设置;}
}
我将实现在模型上自己的验证方法。您的模型最终会看起来像这样:
公共类角色:IValidatableObject {
公众诠释标识{搞定;设置;}
[必需(的ErrorMessage =请输入角色名称)]
公共字符串名称{;设置;}
公共BOOL IsCreator {搞定;设置;}
公共BOOL IsEditor {搞定;设置;}
公共BOOL IsPublisher {搞定;设置;}
公开的IEnumerable<&为ValidationResult GT;验证(ValidationContext validationContext){
如果(this.IsCreator&安培;!&安培;!this.IsEditor和放大器;&安培;!this.IsPublisher)){
收益返回新的ValidationResult(你一定是一个创造者,编辑或出版商);
}
}
}
注意,此时的模型:
- 器具
IValidateableObject
- 有一个方法名为
验证
返回类型的IEnumerable<为ValidationResult>
在模型绑定过程中此方法将自动被调用,如果验证结果返回你的的ModelState
将不再有效。因此,使用在你的控制器这个熟悉的代码将确保除非您的自定义状态,先看看您不采取任何行动:
公开类SomeController {
公众的ActionResult SomeAction(){
如果(ModelState.IsValid){
//做你的东西!
}
}
}
I have view model that have multiple boolean properties, in my controller i have checking ModelState.IsValid
before proceeding to service layer. Now I want to make that ModelState.IsValid
return false
if none of boolean property set to true, is there a way to make it happen?
Here is my sample class
public class Role {
public int Id {get; set;}
[Required(ErrorMessage = "Please enter a role name")]
public string Name {get; set;}
public bool IsCreator {get; set;}
public bool IsEditor {get; set;}
public bool IsPublisher {get; set;}
}
I would implement your own validation method on the model. Your model would end up looking something like this:
public class Role : IValidatableObject {
public int Id {get; set;}
[Required(ErrorMessage = "Please enter a role name")]
public string Name {get; set;}
public bool IsCreator {get; set;}
public bool IsEditor {get; set;}
public bool IsPublisher {get; set;}
public IEnumerable<ValidationResult> Validate(ValidationContext validationContext) {
if (!this.IsCreator && !this.IsEditor && !this.IsPublisher)) {
yield return new ValidationResult("You must be a creator, editor or publisher");
}
}
}
Notice how the model:
- Implements
IValidateableObject
- Has a method named
Validate
which returns the typeIEnumerable<ValidationResult>
During the model binding process this method will automatically be called and if a validation result is returned your ModelState
will no longer be valid. So using this familiar code in your controller will make sure you don't take any action unless your custom conditions check out:
public class SomeController {
public ActionResult SomeAction() {
if (ModelState.IsValid) {
//Do your stuff!
}
}
}
这篇关于ModelState中的验证检查多个布尔属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!