【问题标题】:Blazor displaynameBlazor 显示名称
【发布时间】:2021-05-23 07:39:16
【问题描述】:

我试图找到一种简单的方法来获取模型属性的 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


    【解决方案1】:

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

    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>
    

    【讨论】:

    • 谢谢 Umair。但它给我一个空结果。该类型由模型填充。类型 = {Name = "Scope" FullName = "MyServer.Models.Scope"}。属性很好(类型和名称),但之后没有任何东西在使用它。(attr = null),之后 metadataType = null 然后他返回 string.empty
    猜你喜欢
    • 1970-01-01
    • 2023-02-16
    • 2020-03-14
    • 2021-04-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-07
    相关资源
    最近更新 更多