我需要在现有的ASP.NET MVC 4项目中为许多模型添加StringLengthAttribute
验证,并尝试通过我自己的DataAnnotationsModelMetadataProvider
派生的模型元数据提供程序自动执行此操作。
它与RequiredAttribute
和其他一些数据注释属性完美配合(我得到了客户端和服务器端验证工作),但是没有添加对字符串长度的验证 - 找到下面的最小示例。 / p>
public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes,
Type containerType,
Func<object> modelAccessor,
Type modelType,
string propertyName)
{
StringLengthAttribute lengthAttribute = new StringLengthAttribute(256);
attributes = attributes.Union(new[] { lengthAttribute });
return base.CreateMetadata(attributes,
containerType,
modelAccessor,
modelType,
propertyName);
}
}
所以看起来像StringLengthAttribute
它以某种特殊方式处理。关于如何使其工作或更好的实施想法的任何想法?
答案 0 :(得分:1)
玩完之后,我无法触发StringLength属性。
不理想,但我想另一种解决方案是使用全局ModelValidatorProvider类。当然,你不会得到StringLengthAttribute提供的内置Javascript,你会编写自己的逻辑,但它可以快速解决你以后可以解决的问题吗?
public class MyCustomModelValidatorProvider : ModelValidatorProvider
{
public override IEnumerable<ModelValidator> GetValidators(ModelMetadata metadata, ControllerContext context)
{
return new List<ModelValidator>() { new MyCustomModelValidator(metadata, context) };
}
public class MyCustomModelValidator : ModelValidator
{
public MyCustomModelValidator(ModelMetadata metadata, ControllerContext context)
: base(metadata, context)
{ }
public override IEnumerable<ModelValidationResult> Validate(object container)
{
var model = this.Metadata.Model;
if (model is string)
{
var value = model as string;
if (String.IsNullOrEmpty(value) || value.Length > 256)
{
var validationResult = new ModelValidationResult();
validationResult.Message = (this.Metadata.DisplayName ?? this.Metadata.PropertyName)
+ " needs to be no more then 256 characters";
return new List<ModelValidationResult>() { validationResult };
}
}
return new List<ModelValidationResult>();
}
}
}
将MyCustomModelValidator添加到Global.asax
中的集合 protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
// Use LocalDB for Entity Framework by default
Database.DefaultConnectionFactory = new SqlConnectionFactory(@"Data Source=(localdb)\v11.0; Integrated Security=True; MultipleActiveResultSets=True");
RegisterGlobalFilters(GlobalFilters.Filters);
RegisterRoutes(RouteTable.Routes);
ModelValidatorProviders.Providers.Add(new MyCustomModelValidatorProvider());
}