获取任意类型的属性的显示名称

本文关键字:显示 属性 类型 获取 任意 | 更新日期: 2023-09-27 17:56:28

我很难找到一种干净的方法来做到这一点。我有一个 ViewModel 类,其中包含表的行集合。我希望能够对strongly-typed集合中的类型进行@Html.DisplayNameFor(),而无需引用集合中的第一项或创建该类型的新实例。所以澄清一下,这里有一个例子:

public class TableViewModel
{
  public string Title { get; set; }
  public IEnumerable<Row> Rows { get; set; }
}
public class Row
{
  public int ColumnA { get; set; }
  public int ColumnB { get; set; }
}
//In the Razor view
<table>
  <tr>
    <th>@Html.DisplayNameFor(???)</th>
  </tr>
</table>

有没有办法在不做@Html.DisplayNameFor(x => x.Rows.First().ColumnA)的情况下做到这一点?

获取任意类型的属性的显示名称

可以使用 this.ViewData.ModelMetadata.Properties 集合并调用 GetDisplayName 方法来生成标题单元格内容。我们通常在代码中执行此操作,以将任意模型呈现为表。

编辑:为了对此进行扩展,我使用了一个基本模型来表示一个表,并且只表示一个表。我定义了 3 个类。我有一个TableRowCell' class, a TableRow'类(本质上是TableRowCell对象的集合)和一个Table类。

public class Table
{
    public Table(String name)
    {
        this.Name = name;
        this.ContentRows = new List<TableRow>();
        this.HeaderRow = new TableRow();
        this.FooterRow = new TableRow();
    } 
    public IList<TableRow> ContentRows
    {
        get;
        private set;
    }
    public TableRow FooterRow
    {
        get;
        private set;
    }
    public TableRow HeaderRow
    {
        get;
        private set;
    }
    public String Name
    {
        get;
        private set;
    }
}

当我有一个视图模型,其中包含要在表中显示的对象集合时,我首先调用HtmlHelper扩展,将该集合转换为Table对象。在该方法中,我迭代对 ModelMetadataProviders.Current.GetMetadataForType(null, typeof(TModel)).Properties..Where(item => item.ShowForDisplay) 的调用,以获取用于生成标题单元格的元数据对象的集合。然后,我循环访问项集合并调用 ModelMetadataProviders.Current.GetMetadataForType(() => item, typeof(TModel)).Properties..Where(item => item.ShowForDisplay) 以获取用于生成内容单元格的元数据对象的集合。

从技术上讲,我的HtmlHelper扩展方法实际上返回了一个TableBuilder对象,该对象将具有一个名为Render的方法,用于生成html。到目前为止,这种设置对我很有帮助。

public class TableViewModel
{
  public string Title { get; set; }
  public IEnumerable<Row> Rows { get; set; }
  public Row ForNames = null;
}

@Html.DisplayNameFor(x => x.ForName.ColumnA)