阅读从模型的集合DataAnnotations在MCV2视图 [英] Read DataAnnotations from a collection of models in an MCV2 view

查看:192
本文介绍了阅读从模型的集合DataAnnotations在MCV2视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的MVC2 AdminArea我想建立一个总表的每个我的域模型。
我使用DataAnnotations像下面这些领域模型对象的属性:

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

现在我的问题是:我如何,如果我认为我收到域模型的集合访问displayName属性?我需要它来构建其定义通常外面的表头

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?

在此先感谢!

推荐答案

有是有一个称为静态方法的 ModelMetaData FromLambdaEx pression 。如果你调用它,传递你的财产,随着你的的ViewData ,它将返回 ModelMetaData 的一个实例。那类有应该给你你需要什么显示名称属性。您也可以从该对象的其他元数据信息。

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.

例如,您可以创建一个空的的ViewDataDictionary 对象来获得这些信息。它可以是空的,因为 ModelMetaData 实际上并不使用实例,它只是需要一般的类定义的类型被使用。

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;

第一()方法调用不破,即使你有没有实际的对象,因为拉姆达只是想找到你想要对元数据的属性。同样,你可以D此为一个对象:

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.

这篇关于阅读从模型的集合DataAnnotations在MCV2视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆