首页 > 解决方案 > Blazor 显示名称

问题描述

我试图找到一种简单的方法来获取模型属性的 DisplayName。

DisplayName("FullName")]
    public string Name { get; set; }

在 .razor 页面中,我似乎无法在(示例)标签中获得它,甚至无法在 InputText 中看到它

<label asp-for="Model.Name" class="control-label"></label>


 <InputText class="form-control" DisplayName="Model.Name" @bind-Value="@Model.Name" />

有人知道如何得到这个吗?

标签: blazor.net-5

解决方案


您可以使用以下扩展方法:

public static string GetDisplayName<TModel, TProperty>(this TModel model, Expression<Func<TModel, TProperty>> expression) 
{
    Type type = typeof(TModel);

    MemberExpression memberExpression = (MemberExpression)expression.Body;
    string propertyName = ((memberExpression.Member is PropertyInfo) ? memberExpression.Member.Name : null);

    // First look into attributes on a type and it's parents
    DisplayAttribute attr;
    attr = (DisplayAttribute)type.GetProperty(propertyName).GetCustomAttributes(typeof(DisplayAttribute), true).SingleOrDefault();

    // Look for [MetadataType] attribute in type hierarchy
    // http://stackoverflow.com/questions/1910532/attribute-isdefined-doesnt-see-attributes-applied-with-metadatatype-class
    if (attr == null) {
        MetadataTypeAttribute metadataType = (MetadataTypeAttribute)type.GetCustomAttributes(typeof(MetadataTypeAttribute), true).FirstOrDefault();
        if (metadataType != null) {
            var property = metadataType.MetadataClassType.GetProperty(propertyName);
            if (property != null) {
                attr = (DisplayAttribute)property.GetCustomAttributes(typeof(DisplayNameAttribute), true).SingleOrDefault();
            }
        }
    }
    return (attr != null) ? attr.Name : String.Empty;
}

并这样称呼它:

HelperNamespace.GetDisplayName(YourClass, m => m.Name)

如果你想在 Blazor 中使用它,你可以这样做:

<label class="control-label">@(HelperNamespace.GetDisplayName(YourClass, m => m.Name))</label>

推荐阅读