DataAnnotationsModelMetadataProvider を使用して、複数の dataannotation 属性を 1 つのカスタムに置き換えようとしています。
だから私は偽の属性を作成しました:
public class TestAttribute : ValidationAttribute
{
}
そして、この属性でモデル プロパティを装飾します。
DataAnnotationsModelMetadataProvider を使用して、TestAttribute が設定されているかどうかに基づいて、他のいくつかの属性を追加します。
public class MyCustomMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes, Type containerType, Func<object> modelAccessor, Type modelType, string propertyName)
{
var attributeList = attributes.ToList();
if (attributeList.OfType<TestAttribute>().Any())
{
var req = new RequiredAttribute();
attributeList.Add(req);
}
return base.CreateMetadata(attributeList, containerType, modelAccessor, modelType, propertyName);
}
}
これは機能します。test 属性を持つプロパティが必須になりました。
機能しないのは、 RequiredAttribute オブジェクトのプロパティを設定することです..次のように:
var attributeList = attributes.ToList();
if (attributeList.OfType<CurrencyAttribute>().Any())
{
var req = new RequiredAttribute();
req.ErrorMessage = "Test test";
attributeList.Add(req);
}
エラー メッセージは「xx フィールドが必要です」のままです。
何故ですか?