MVC只显示有价值的模型属性?

时间:2015-07-12 00:56:30

标签: c# asp.net asp.net-mvc entity-framework asp.net-mvc-5

好吧,所以我的模型包含200多个属性或字段,使用Entity框架,这反映到数据库中有1行200列。在视图中显示此模型时,希望显示仅包含数据或值的字段或属性。

现在我可以浏览每一个并检查它是否有价值!但我想知道是否有更好的方法,所以我不必加载大厅模型,这将是90%无效!?

1 个答案:

答案 0 :(得分:2)

是的,你可以使用反射,每个和这里都有一个样本

@{
    var properties = Model.GetType().GetProperties();
}

@foreach(System.Reflection.PropertyInfo info in properties){
   var value = info.GetValue(Model,null);
   if(value!=null){
       <b>@info.Name</b> <i>@value</i>
   }
}

这是一个有效的demo

在演示中,我设置了问题值,并将answer属性保留为默认值“null”,因此将显示问题并且答案不会因为它具有空值

<强> EDITED 获取显示属性值,这里你可以做什么

// to get the display Name
var da =info.GetCustomAttributes(typeof(DisplayAttribute),false)
            .Cast<DisplayAttribute>();
if(da.Count()>0) //to ensure that there is a [Display attribute
{
        <p>Display Name:<i>@da.First().Name</i></p>
}

我也修改了演示以反映结果

希望它会帮助你