I am aware that in a custom display or editor template I can get metadata about the model via ViewData.ModelMetadata, which has properties that indicate whether certain metadata attributes have been defined for the property, such as IsRequired, DisplayName, and so on. But is there anyway I can access custom metadata I’ve added to the property via custom attributes?
For example, say in my view I have a property like so:
[UIHint("Whizbang")]
[SomeAttribute("foobar")]
public string LeftWhizbang { get; set; }
And I have a custom display template named Whizbang.cshtml with the following content:
@model string
Left Whizbang Value: @Model
What I’d like to do is be able to determine whether the property LeftWhizbang is decorated with the attribute SomeAttribute and, if so, I’d like to access the attribute’s Message property (say), namely the value “foobar”.
I’d like to be able to do something like this in my template:
@model string
Left Whizbang Value: @Model
@{
SomeAttributeAttribute attr = ViewData.ModelMetadata.GetAttributes(...);
if (attr != null)
{
<text>... and the value is @attr.Message</text>
}
}
Is this at all possible, or am I looking down a dead end?
Sure. First you’ll need your attribute which implements
IMetadataAwareso thatDataAnnotationsModelMetadataProviderknows about itYou can then access the attribute by creating a helper method: