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
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)) {
// ...
}