使用反射模型属性显示名称 [英] Model Property Display Name using Reflection

查看:108
本文介绍了使用反射模型属性显示名称的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在做一个项目,需要在屏幕上输出几百个属性.为了节省很多繁琐的标记,我决定使用反射.

I am working on a project where I need to output a few hundred properties on to the screen. To save myself lots of tedious markup, I decided to use reflection.

//markup removed to keep this concise
@for (var i = 0; i < Model.SiteAndJobDetails.GetType().GetProperties().Count(); i++)
{
  @Model.SiteAndJobDetails.GetType().GetProperties()[i].Name
  @Model.SiteAndJobDetails.GetType().GetProperties()[i].GetValue(Model.SiteAndJobDetails, null)
}

尽管渲染速度较慢,但​​可以节省使用HTML帮助程序编写大约200个属性和值的时间.至少那是计划.但是,我需要使用@Html.DisplayNameFor或类似的东西来从属性中获取Display属性值.

Although slower to render, this will save me writing out about 2 hundred properties and values with HTML helpers. At least, that was the plan. However, I need to use @Html.DisplayNameFor or something similar to pick up the Display attribute value from the property.

我最初的想法是

@Html.DisplayNameFor(m=>@Model.SiteAndJobDetails.GetType().GetProperties()[i].Name)

但是我认为这是行不通的,因为我在这里使用反射来获取属性名称.还有另一种方法吗?

But that does not work, I would imagine because I am using reflection here to get the property name. Is there another way?

推荐答案

@Andrei正确使用ViewData.ModelMetadata,但语法略有偏离.正确的语法是

@Andrei was correct to use the ViewData.ModelMetadata but had the syntax slightly off. The correct syntax is

@ViewData.ModelMetadata.Properties.First(x => x.PropertyName == "SiteAndJobDetails")
.Properties.SingleOrDefault(x => x.PropertyName == Model.SiteAndJobDetails.GetType().GetProperties()[i].Name)
.DisplayName

最后的解决方案是检查属性是否存在(如果确实使用过),否则使用属性名称

The final solution is to check the property exists, if it does use it, otherwise use the property name

@if (!string.IsNullOrEmpty(@ViewData.ModelMetadata.Properties.First(x => x.PropertyName == "SiteAndJobDetails").Properties.SingleOrDefault(x => x.PropertyName == Model.SiteAndJobDetails.GetType().GetProperties()[i].Name).DisplayName))
{
    @ViewData.ModelMetadata.Properties.First(x => x.PropertyName == "SiteAndJobDetails").Properties.SingleOrDefault(x => x.PropertyName == Model.SiteAndJobDetails.GetType().GetProperties()[i].Name).DisplayName
}
else
{
    @Model.SiteAndJobDetails.GetType().GetProperties()[i].Name
}

这篇关于使用反射模型属性显示名称的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆