blazor - 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" />
有人知道如何得到这个吗?
解决方案
您可以使用以下扩展方法:
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>
推荐阅读
- bash - 如何创建 solr 服务以在重启时启动 solr
- python - 温度转换器。如何接受负数作为输入?
- if-statement - sas 如果没有观察则停止执行
- java - 如何为打印“Hello, World!”的 main 方法编写 Junit 字符串到控制台并使用 Spring Framework
- gis - 如何在 Google 地球的 KMZ 线上启用突出显示?
- selenium - Selenium Grid UnreachableBrowserException
- stripe-payments - 查询每个客户的所有费用的 Stripe API?
- python - 在熊猫的DataFrame中删除相互抵消的数字
- typo3 - TYPO3 扩展 - 属性映射器无法识别外部域类
- javascript - JavaScript 中的可撤销代理有什么用?