さまざまな人がさまざまな名前で表示する必要のあるフィールドがあります。
たとえば、次のユーザータイプがあるとします。
public enum UserType {Expert, Normal, Guest}
IMetadataAware
属性を実装しました:
[AttributeUsage(AttributeTargets.Property, AllowMultiple = true)]
public class DisplayForUserTypeAttribute : Attribute, IMetadataAware
{
private readonly UserType _userType;
public DisplayForUserTypeAttribute(UserType userType)
{
_userType = userType;
}
public string Name { get; set; }
public void OnMetadataCreated(ModelMetadata metadata)
{
if (CurrentContext.UserType != _userType)
return;
metadata.DisplayName = Name;
}
}
必要に応じて他の値をオーバーライドできますが、オーバーライドしない場合はデフォルト値にフォールバックするという考え方です。例えば:
public class Model
{
[Display(Name = "Age")]
[DisplayForUserType(UserType.Guest, Name = "Age (in years, round down)")]
public string Age { get; set; }
[Display(Name = "Address")]
[DisplayForUserType(UserType.Expert, Name = "ADR")]
[DisplayForUserType(UserType.Normal, Name = "The Address")]
[DisplayForUserType(UserType.Guest, Name = "This is an Address")]
public string Address { get; set; }
}
問題は、同じタイプの属性が複数ある場合、最初の属性に対してDataAnnotationsModelMetadataProvider
のみ実行OnMetadataCreated
されることです。
上記の例では、Address
「アドレス」または「ADR」としてのみ表示できます。他の属性は実行されません。
異なる属性を使用しようとすると、、、、、DisplayForUserType
すべてDisplayForUserType2
がDisplayForUserType3
期待どおりに機能します。
私はここで何か間違ったことをしていますか?