簡體   English   中英

MVC顯示模型屬性僅具有價值嗎?

[英]MVC display model properties that has value only?

好了,因此我的模型使用Entity Framework包含200多個屬性或字段,這反映到1行200列的數據庫中。 在視圖中顯示此模型時,只想顯示僅具有數據或值的字段或屬性。

現在,我可以檢查每一個,並檢查它是否有價值! 但我想知道是否有更好的方法,這樣我就不必加載將為90%null的大廳模型了!

是的,您可以使用反射,這里還有一個示例

@{
    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>
   }
}

這是一個工作演示

在演示中,我設置了問題值,並且將answer屬性保留為默認的“ null”,結果將顯示問題,而答案將不存在,因為它具有null值

編輯以獲取顯示屬性值,在這里您可以做什么

// 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>
}

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

希望對你有幫助

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM