I would like to be able to test a property for the [AllowHtml] attribute from within an editor template.
It doesn't seem to be lurking within ViewData.ModelMetadata
.
I've tried iterating through ViewData.ModelMetadata.AdditionalValues
to see if it's there, but it doesn't appear to be.
I've scoured Google and Brad Wilson's post on templates, but I can't find the answer anywhere.
I believe you'll have to do some heavy lifting in the template like:
var allowHtmlAttribute = this.ViewData.ModelMetadata
.ContainerType
.GetProperty(this.ViewData.ModelMetadata.PropertyName)
.GetCustomAttributes(typeof(AllowHtmlAttribute), false)
.Select(a => a as AllowHtmlAttribute)
.FirstOrDefault(a => a != null);
and now that I think about it, a Extension Method would be great!
public static class ModelMetadataExtensions
{
public T GetPropertyAttribute<T>(this ModelMetadata instance)
where T : Attribute
{
var result = instance.ContainerType
.GetProperty(instance.PropertyName)
.GetCustomAttributes(typeof(T), false)
.Select(a => a as T)
.FirstOrDefault(a => a != null);
return result;
}
}
Then
var myAttribute = this.ViewData.ModelMetadata
.GetPropertyAttribute<AllowHtmlAttribute>();