我已经使用了链接中的上述自定义属性(MVC3 unobtrusive validation group of inputs),但对其进行了很少的修改。我正在检查我需要的 List 而不是字符串作为属性类型。对我来说,验证工作正常。但是没有显示错误消息。当我调试时,我发现在要验证的属性的数据注释中设置的错误消息在自定义验证器构造函数中为 null。我尝试了硬编码错误消息和来自资源包的错误消息。
请让我知道如何解决这个问题。
我的代码供参考。
使用以下属性的属性
[AtLeastOneRequired("List1", "List2", ErrorMessage = "Test Error Message", ErrorMessageResourceType = typeof(Motorola.MWM.Web.Resources.MWMResource), ErrorMessageResourceName = "ERROR_MSG_USER_GROUP")]
public List<string> List1 { get; set; }
public List<string> List2 { get; set; }
public class AtLeastOneRequiredAttribute : ValidationAttribute, IClientValidatable
{
private readonly string[] _properties;
public AtLeastOneRequiredAttribute(params string[] properties)
{
_properties = properties;//properties are populated
Console.WriteLine(ErrorMessage);//but error message is null
}
protected override ValidationResult IsValid(object value, ValidationContext validationContext)
{
if (_properties == null || _properties.Length < 1)
{
return null;
}
foreach (var property in _properties)
{
var propertyInfo = validationContext.ObjectType.GetProperty(property);
if (propertyInfo == null)
{
return new ValidationResult(string.Format("unknown property {0}", property));
}
var propertyValue = propertyInfo.GetValue(validationContext.ObjectInstance, null);
if (propertyInfo.GetType().IsGenericType && (propertyValue as List<string>) != null && (propertyValue as List<string>).Count > 0)
{
return null;
}
}
return new ValidationResult(FormatErrorMessage(validationContext.DisplayName));
}
public IEnumerable<ModelClientValidationRule> GetClientValidationRules(ModelMetadata metadata, ControllerContext context)
{
var rule = new ModelClientValidationRule
{
ErrorMessage = ErrorMessage,
ValidationType = "atleastonerequired"
};
rule.ValidationParameters["properties"] = string.Join(",", _properties);
yield return rule;
}
}
提前致谢, 穆拉利