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!
There is a
ModelMetaData
class that has a static method calledFromLambdaExpression
. If you call it and pass in your property, along with yourViewData
, it will return an instance ofModelMetaData
. That class has aDisplayName
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 theModelMetaData
doesn't actually use the instance, it just needs the generic class to define the type being used.The
First()
method call doesn't break even if you have no actualPerson
object because the lambda is simply trying to find the property you want the meta data about. Similarly, you could d this for a singlePerson
object:You could clean this up significantly with a helper or extension method, but this should put you on the right path.
Alright, I followed sgriffinusa's advise (thanks again!) and created a strongly typed HtmlHelper:
Of course TModel still is a collection of domain models like stated in my inital question but we can call the helper in the view like this: