Reading data Annotations from the collection of models in the MCV2 view

In my MVC2 AdminArea, I would like to create a summary table for each of my domain models. I use DataAnnotations as shown below for the properties of these 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 create table headers that are defined outside of normal

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

loops. Inside this loop, I can write

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

but is there a way to access this information using a collection of elements instead of a specific instance?

Thanks in advance!

+5
source share
2 answers

ModelMetaData, , FromLambdaExpression. , ViewData, ModelMetaData. DisplayName, , . .

, ViewDataDictionary, . , ModelMetaData , .

//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;

First() , Person, , . , d Person:

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

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

, .

+2

, sgriffinusa ( !) HtmlHelper:

public static MvcHtmlString MetaDisplayName<TModel, TProperty>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TProperty>> expression) where TModel : class
{
    ModelMetadata metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
    return MvcHtmlString.Create(metadata.GetDisplayName());
}

, TModel - , , :

<%: Html.MetaDisplayName(p => p.First().Name) %>
0

All Articles