加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > asp.Net > 正文

asp.net-mvc – ASP.NET MVC:访问集合中项目的ModelMetadata

发布时间:2020-12-16 04:07:59 所属栏目:asp.Net 来源:网络整理
导读:我正在尝试为Index视图编写一个自动脚手架.我希望能够传递模型或视图模型的集合(例如,IEnumerable MyViewModel)并返回一个 HTML表,该表使用标题属性(th元素)和 Html.Display(propertyName)的DisplayName属性)对于细胞(td元素).每行应对应于集合中的一个项目.
我正在尝试为Index视图编写一个自动脚手架.我希望能够传递模型或视图模型的集合(例如,IEnumerable< MyViewModel>)并返回一个 HTML表,该表使用标题属性(th元素)和 Html.Display(propertyName)的DisplayName属性)对于细胞(td元素).每行应对应于集合中的一个项目.

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

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

解决方法

一个简单的扩展方法可以完成这项工作:
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) %>

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读