ASP.NET MVC:访问集合中项目的模型元数据

发布于 2024-08-25 10:09:03 字数 412 浏览 0 评论 0原文

我正在尝试为索引视图编写一个自动脚手架。我希望能够传入模型或视图模型的集合(例如 IEnumerable)并获取使用 DisplayName 的 HTML 表标题的属性(th 元素)和单元格的 Html.Display(propertyName)td 元素)。每一行应对应于集合中的一项。

当我仅显示一条记录时(如在“详细信息”视图中),我使用 ViewData.ModelMetadata.Properties 来获取给定模型的属性列表。但是,当我传递给视图的模型是模型或视图模型对象的集合而不是模型或视图模型本身时,会发生什么情况?

如何获取集合中特定项目的 ModelMetadata?

I'm trying to write an auto-scaffolder for Index views. I'd like to be able to pass in a collection of models or view-models (e.g., IEnumerable<MyViewModel>) and get back an HTML table that uses the DisplayName attribute for the headings (th elements) and Html.Display(propertyName) for the cells (td elements). Each row should correspond to one item in the collection.

When I'm only displaying a single record, as in a Details view, I use ViewData.ModelMetadata.Properties to obtain the list of properties for a given model. But what happens when the model I pass to the view is a collection of model or view-model objects and not a model or view-model itself?

How do I obtain the ModelMetadata for a particular item in a collection?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光清浅 2024-09-01 10:09:03

一个简单的扩展方法可能可以完成这项工作:

public static class MyExtensions
{
    public static ModelMetadata GetMetadata<TModel>(this TModel model)
    {
        return ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel));
    }
}

在您看来:

<%@ Page 
    Language="C#"
    Inherits="System.Web.Mvc.ViewPage<System.Collections.Generic.IEnumerable<MyViewModel>>" %>

<%-- Get metadata for the first item in the model collection --%>
<%= Html.Encode(Model.ElementAt(0).GetMetadata().ModelType) %>

A simple extension method might do the job:

public static class MyExtensions
{
    public static ModelMetadata GetMetadata<TModel>(this TModel model)
    {
        return ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel));
    }
}

And in your view:

<%@ Page 
    Language="C#"
    Inherits="System.Web.Mvc.ViewPage<System.Collections.Generic.IEnumerable<MyViewModel>>" %>

<%-- Get metadata for the first item in the model collection --%>
<%= Html.Encode(Model.ElementAt(0).GetMetadata().ModelType) %>
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文