Create custom display attribute using or inherits DisplayAttribute in ASP.NET MVC
In order to set a specific display name for your property, you need to set the metadata property DisplayName
. If you need to write custom attributes, you need to make sure that you create a custom metadata provider. Inside you need to set the DisplayName
of your property, based on the values provided.
public class CustomModelMetadataProvider : DataAnnotationsModelMetadataProvider
{
protected override ModelMetadata CreateMetadata(IEnumerable<Attribute> attributes,
Type containerType, Func<object> modelAccessor,
Type modelType, string propertyName)
{
var modelMetadata = base.CreateMetadata(attributes, containerType,
modelAccessor, modelType, propertyName);
if (attributes.OfType<MyDisplay>().ToList().Count > 0)
{
modelMetadata.DisplayName = GetValueFromLocalizationAttribute(attributes.OfType<MyDisplay>().ToList()[0]);
}
return modelMetadata;
}
private string GetValueFromLocalizationAttribute(MyDisplay attribute)
{
return computedValueBasedOnCodeAndLanguage;
}
}
You are doing it wrong. The DisplayAttribute already supports 'translations' using the built-in .net internationalization
[Display(Name = "property_name", ResourceType = typeof(MyResources))]
Only if that's not enough you should create your own attribute, but not deriving from Display.
Edit:
The DisplayAttribute
is a sealed class, so there is no way to inherit from it.