Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read DataAnnotations from a collection of models in an MCV2 view

In my MVC2 AdminArea I'd like to create an overview table for each of my domain models. I am using DataAnnotations like the following for the properties of those domain model objects:

[DisplayName("MyPropertyName")]
public string Name { get; set; }

Now my question is: How can I access the DisplayName Attribute if my view receives a collection of my domain models? I need this to build the table headers which are defined outside of the usual

<% foreach (var item in Model) { %>

loop. Inside this loop I can write

<%: Html.LabelFor(c => item.Name) %>

but is there any way to access this information using the collection of items instead of a concrete instance?

Thanks in advance!

like image 464
Shackles Avatar asked Nov 05 '22 05:11

Shackles


1 Answers

There is a ModelMetaData class that has a static method called FromLambdaExpression. If you call it and pass in your property, along with your ViewData, it will return an instance of ModelMetaData. That class has a DisplayName property that should give you what you need. You can also get other meta data information from this object.

For example, you can create an empty ViewDataDictionary object to get this information. It can be empty because the ModelMetaData doesn't actually use the instance, it just needs the generic class to define the type being used.

//This would typically be just your view model data.    
ViewDataDictionary<IEnumerable<Person>> data = new ViewDataDictionary<IEnumerable<Person>>();

ModelMetadata result = ModelMetadata.FromLambdaExpression(p => p.First().Name, data);
string displayName = result.DisplayName;

The First() method call doesn't break even if you have no actual Person object because the lambda is simply trying to find the property you want the meta data about. Similarly, you could d this for a single Person object:

//This would typically be just your view model data.    
ViewDataDictionary<Person> data = new ViewDataDictionary<Person>();

ModelMetadata result = ModelMetadata.FromLambdaExpression(p => p.Name, data);

You could clean this up significantly with a helper or extension method, but this should put you on the right path.

like image 145
sgriffinusa Avatar answered Nov 09 '22 14:11

sgriffinusa