从 MCV2 视图中的模型集合中读取 DataAnnotations
在我的 MVC2 AdminArea 中,我想为每个域模型创建一个概述表。 我正在使用如下所示的 DataAnnotations 作为这些域模型对象的属性:
[DisplayName("MyPropertyName")]
public string Name { get; set; }
现在我的问题是:如果我的视图收到域模型的集合,如何访问 DisplayName 属性?我需要它来构建在通常循环之外定义的表头
<% foreach (var item in Model) { %>
。在这个循环中,我可以编写
<%: Html.LabelFor(c => item.Name) %>
,但是有什么方法可以使用项目集合而不是具体实例来访问此信息?
提前致谢!
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!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
有一个 ModelMetaData 类,它有一个名为 FromLambdaExpression 的静态方法。如果您调用它并传入您的属性以及
ViewData
,它将返回ModelMetaData
的实例。该类有一个DisplayName
属性,应该可以满足您的需要。您还可以从此对象获取其他元数据信息。例如,您可以创建一个空的 ViewDataDictionary 对象来获取此信息。它可以为空,因为 ModelMetaData 实际上并不使用实例,它只需要泛型类来定义所使用的类型。
即使您没有实际的
Person
对象,First()
方法调用也不会中断,因为 lambda 只是尝试查找您想要元数据的属性。同样,您可以为单个Person
对象进行此操作:您可以使用辅助方法或扩展方法来显着清理它,但这应该会让您走上正确的道路。
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.
好吧,我听从了 sgriffinusa 的建议(再次感谢!)并创建了一个强类型的 HtmlHelper:
当然,TModel 仍然是域模型的集合,就像我最初的问题中所述,但我们可以在视图中调用助手像这样:
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: