Skip to content

Instantly share code, notes, and snippets.

@relyky
Last active August 14, 2024 11:31
Show Gist options
  • Save relyky/3af55c2440bab9580b4ba15b5ef5bc95 to your computer and use it in GitHub Desktop.
Save relyky/3af55c2440bab9580b4ba15b5ef5bc95 to your computer and use it in GitHub Desktop.
C#, get property Display Name of DisplayAttribute, DataAnnotations, MemberExpression
using System;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Linq.Expressions;
/// <summary>
/// global type handling helper
/// </summary>
public static class GT<TModel>
{
/// <summary>
/// get DisplayAttribute Name of a property of Type
/// </summary>
public static string Display<TProperty>(Expression<Func<TModel, TProperty>> f)
{
var exp = f.Body as MemberExpression;
var property = exp.Expression.Type.GetProperty(exp.Member.Name);
var attr = property?.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;
return attr?.GetName() ?? exp.Member.Name;
}
}
/// <summary>
/// global type handling helper
/// </summary>
public static class GT
{
/// <summary>
/// get DisplayAttribute Name of a property of a model
/// </summary>
public static string Display<TProperty>(Expression<Func<TProperty>> f)
{
var exp = f.Body as MemberExpression;
var property = exp.Expression.Type.GetProperty(exp.Member.Name);
var attr = property?.GetCustomAttributes(typeof(DisplayAttribute), false).FirstOrDefault() as DisplayAttribute;
return attr?.GetName() ?? exp.Member.Name;
}
}
/// ===========================================
/// test case
class MyModel
{
[Display(Name = "厚厚厚")]
public decimal Foo { get; set; }
public decimal Bar { get; set; }
}
class Program
{
static void Main(string[] args)
{
string a1 = GT<MyModel>.Display(m => m.Foo);
string a2 = GT<MyModel>.Display(m => m.Bar);
MyModel model = new MyModel();
string b1 = GT.Display(() => model.Foo);
string b2 = GT.Display(() => model.Bar);
Console.WriteLine($"{a1}, {a2}");
Console.WriteLine($"{b1}, {b2}");
Console.WriteLine("Press any key to continue.");
}
}
//>>>>>>>>>>>>>>>>>>>>>>>
//>>> 厚厚厚, Bar
//>>> 厚厚厚, Bar
//>>> Press any key to continue.
///
/// 應用 @Utils.Display(For) 實作自訂 Label razor component.
/// 使用範例:<Label For="()=>model.FooProperty" />
/// 使用範例:<Label Title="欄位名稱" />
///
@using System
@using System.Linq
@using System.Linq.Expressions
@typeparam TProp <--- generic type 泛型
@if (Title != null)
{
<label>@Title</label>
}
else if (For != null)
{
@* 自 Property 的 DisplayAttribute 屬性取 Title。 *@
<label>@GT.Display(For)</label>
}
else
{
<label></label>
}
@code{
[Parameter] public Expression<Func<TProp>> For { get; set; }
[Parameter] public string Title { get; set; }
}
@swati-oss
Copy link

p.displayName = p.name + " [from " + f.id + "]";

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment