How to get a UIHint attribute value from an MVC Razor view
1 min read
The UIHint Attribute is a great way to pass metadata from a model to a view. I was looking around for a simple way to get the value of the attribute from my razor view. I could be missing something obvious, but I couldn’t find anything. Brad Wilson has some great posts about ModelMetadata if you want to look at in more depth.
You set UIHint Attributes in your model like this:
[DataMember][UIHint("Hidden")]public string Key { get; set; }
```text
You could write a custom ModelMetadata provider and so on to get it or you can do what I did and write a simple extension method on PropertyInfo to grab the data. I will expand on the design later, but it meets my needs right now.
```csharp
public static class PropertyInfoExtensions{ public static bool IsHidden(this PropertyInfo property) { return string.Compare(ModelMetadataProviders. Current.GetMetadataForProperty(null, property.DeclaringType, property.Name).TemplateHint, "Hidden") == 0; }}
```text
And then in your view you just call IsHidden
```csharp
@foreach (var prop in Model.GetType().GetProperties()){ <td> if(!prop.IsHidden()) { @prop.GetValue(Model, null) } </td>}Share: