我有一個要求,以將StringLengthAttribute
驗證添加到現有的ASP.NET MVC 4項目中的很多模型,並試圖通過我自己的模型元數據提供程序從DataAnnotationsModelMetadataProvider
派生自動執行此操作。通過自定義DataAnnotationsModelMetadataProvider添加StringLengthAttribute
它與RequiredAttribute
和一些其他數據註釋屬性(我得到客戶端和服務器端驗證工作)完美的工作,但不添加字符串長度的驗證 - 找到下面的最小示例。
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
它以某種特殊的方式處理。關於如何使其工作或更好的實施想法的任何想法?
我想我會採取這種做法現在,謝謝! –