Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Display only selected properties from the class

Assume, I like to display only name and quantity from the class (not "price"). How to set visible property for these fields in the ItemPoints.cs, which I could make use of in razor page to display only these two properties.

Below is my class:

ItemPoints.cs

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

public class ItemPoints : Points 
{        
    [JsonPropertyName("nme")]
    public double Name { get; set; }

    [JsonPropertyName("Prc")]
    public double Price { get; set; }
  
    [JsonPropertyName("qty")]
    public double Quantity{ get; set; }    
 }

Razor page that displays these properties:

Item.Razor

   var type = typeof(ItemPoints); // I could pass different types here
   foreach (var item in type.GetProperties().Where(w => w.PropertyType == typeof(double)))
   {
         .......
   }

As you could see var type = typeof(ItemPoints), I could pass different types here. So do not want to hardcode class name and property name in razor page. Thank you.

>Solution :

I suggest to use a custom attribute to mark properties that you doesn’t want to display. Something like this.

public class HiddenAttribute : Attribute { }

public class ItemPoints : Points   {
    [JsonPropertyName("nme")]
    public double Name { get; set; }

    [Hidden]
    [JsonPropertyName("Prc")]
    public double Price { get; set; }

    [JsonPropertyName("qty")]
    public double Quantity { get; set; }
}

And then exclude hidden properties from the foreach:

foreach (var item in type
              .GetProperties()
              .Where(w => 
                   w.PropertyType == typeof(double) && 
                   w.GetCustomAttribute<HiddenAttribute>() == null)) {

    // ...
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading