I have fields that different people should see in different names.
For example, suppose I have the following user types:
public enum UserType {Expert, Normal, Guest}
I implemented an IMetadataAware
attribute:
[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;
}
}
The idea is that I can override other values as needed, but fall back on default values when I don't. For example:
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; }
}
The problem is that when I have multiple attributes of the same type, DataAnnotationsModelMetadataProvider
only runs OnMetadataCreated
for the first one.
In the example above, Address
can only be shown as "Address" or "ADR" - the other attributes are never executed.
If I try to use different attributes - DisplayForUserType
, DisplayForUserType2
, DisplayForUserType3
, everything is working as expected.
Am I doing anything wrong here?
TypeId
. Here's a good explanation if anyone is interested: Should the TypeIds of two attributes which are semantically identical be different or the same? Thanks a lot, and (a late) welcome to Stack Overflow! – Lindsylindy