如何在ItemPoints.cs设置属性可见性,在Razor页面仅显示指定属性
解决方法
1. 自定义标记特性
先写一个专属特性类,用来标记需要在Razor页面展示的属性:
[AttributeUsage(AttributeTargets.Property, Inherited = false, AllowMultiple = false)] public class ShowInRazorAttribute : Attribute { // 仅作为标识使用,无需额外逻辑 }
2. 在ItemPoints类中标记目标属性
给需要显示的Name和Quantity加上这个特性,Price不做标记,以此区分可见性:
public class ItemPoints : Points { [JsonPropertyName("nme")] [ShowInRazor] public double Name { get; set; } [JsonPropertyName("Prc")] public double Price { get; set; } [JsonPropertyName("qty")] [ShowInRazor] public double Quantity{ get; set; } }
3. 调整Razor页面的反射逻辑
修改反射筛选条件,只保留带有ShowInRazor特性且类型为double的属性,这样不管传入什么类型都能通用:
var type = typeof(ItemPoints); // 可替换为任意传入的类型 var showAttrType = typeof(ShowInRazorAttribute); foreach (var prop in type.GetProperties() .Where(prop => prop.PropertyType == typeof(double) && prop.GetCustomAttributes(showAttrType, false).Any())) { // 此处编写属性显示逻辑,例如输出属性名与对应值 // 示例:<p>@prop.Name: @prop.GetValue(你的数据实例)</p> }
这种方式的优势:
- 无需硬编码类名或属性名,完全通过特性标记控制显示规则
- 支持任意传入类型,只要目标属性标记了
ShowInRazor就能被筛选出来 - 后续调整显示属性只需增删特性标记,维护成本低
内容的提问来源于stack exchange,提问作者st27
相关产品推荐
相关产品推荐

