【问题标题】:ASP.NET MVC: Accessing ModelMetadata for items in a collectionASP.NET MVC:访问集合中项目的 ModelMetadata
【发布时间】:2010-03-14 16:56:26
【问题描述】:

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

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

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

【问题讨论】:

    标签: asp.net-mvc templates asp.net-mvc-2 html-helper scaffolding


    【解决方案1】:

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

    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) %>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-27
      • 1970-01-01
      • 2018-06-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多