alright , so my model contains more than 200 properties or fields, using Entity framework , this reflect into the database with 1 row with 200 column. when showing this model in the view, would like to show the fields or properties which has data or value only.
now i can go through each one and check if it has value or not! but i would like to know if there is a better way so i don't have to load the hall model which going to be 90% null !?
Yes you can using reflection and for each and here a sample
@{
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>
}
}
here a working demo
In the demo, i set the question value and I kept the answer property as default "null", as a result the question will be displayed and answer will not since it has null value
EDITED to get the display attribute value, here what you can do
// 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>
}
I did modify the demo also to reflect the result
hope it will help you