我确实有一个带有某些必需属性的实体类,具体取决于选择器。
例如:选择器可以假定为“ 1”或“ 2”。如果选择器为“ 1”,则需要一组参数。如果选择器为“ 2”,则需要另一组参数。
class MyClass{
public int Selector {get;set;} // 1 or 2
public string A_required_for_1 {get;set;}
public string B_required_for_1 {get;set;}
public string C_required_for_2 {get;set;}
public string D_required_for_2 {get;set;}
public string E_Required_for_both_selectors {get;set;}
}
用户应该能够在视图中的“创建”或“编辑”操作期间在选择器之间切换。
客户端验证已解决。
如何在服务器验证中处理它?
您可以创建自己的自定义验证属性,也可以使用MVC Foolproof验证,然后执行以下操作:
class MyClass
{
public int Selector {get;set;} // 1 or 2
[RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")]
public string A_required_for_1 {get;set;}
[RequiredIf("Selector == 1", ErrorMessage = "Your Error Message")]
public string B_required_for_1 {get;set;}
[RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")]
public string C_required_for_2 {get;set;}
[RequiredIf("Selector == 2", ErrorMessage = "Your Error Message")]
public string D_required_for_2 {get;set;}
[Required("Your Error Message")]
public string E_Required_for_both_selectors {get;set;}
}
正如Win所提到的,它似乎并没有处于活跃的开发阶段,因此您可能想沿着创建自己的自定义验证属性的路走,这确实需要做更多的工作,但是您可以更好地控制验证本身。选择根据您的需要。
对于自定义验证属性,您可以执行以下操作:
public class RequiredIfOtherProperty : ValidationAttribute
{
private readonly string _otherPropertyName;
private readonly string _compareValue;
public RequiredIfOtherProperty(string otherPropertyName, string compareValue)
{
_otherPropertyName = otherPropertyName;
_compareValue = compareValue;
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
var otherProperty = validationContext.ObjectType.GetProperty(_otherPropertyName);
if (otherProperty == null)
{
return new ValidationResult($"Property '{_otherPropertyName}' does not exist");
);
var otherPropertyValue = otherProperty.GetValue(validationContext.ObjectInstance, null);
if (!_compareValue.Equals(otherPropertyValue))
{
return new ValidationResult(this.FormatErrorMessage(validationContext.DisplayName));
}
return null;
}
}
它应该使您大致了解可以做什么,并且可以将实际验证更改为自己喜欢的方式。然后,您可以像普通属性一样使用它,例如
[RequiredIfOtherProperty("SomeProperty", "ValueToCompareWith")]
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句