c# - 获取CSHTML中[Description]的属性值
问题描述
我想在属性/字段的cshtml描述中Description
使用
DisplayName
是否可以像使用一样容易地做到这一点,@Html.DisplayNameFor(x => ...)
或者我必须“提取它”
public class Test
{
[Description("Test description")]
public bool Name { get; set; }
}
我一直在尝试类似的东西,但没有任何成功
var desc = typeof(Test)
.GetCustomAttributes(false)
.ToDictionary(a => a.GetType().Name, a => a);
或者
typeof(Test).Attributes
typeof(Test).GetCustomAttributesData();
解决方案
您可以简单地为此编写一个自定义 HtmlHelper:
public static class HtmlHelpers
{
public static IHtmlContent DescriptionFor<TModel, TValue>(this IHtmlHelper<TModel> html, Expression<Func<TModel, TValue>> expression)
{
if (expression == null)
throw new ArgumentNullException(nameof(expression));
DescriptionAttribute descriptionAttribute = null;
if (expression.Body is MemberExpression memberExpression)
{
descriptionAttribute = memberExpression.Member
.GetCustomAttributes(typeof(DescriptionAttribute), false)
.Cast<DescriptionAttribute>()
.SingleOrDefault();
}
return new HtmlString(descriptionAttribute?.Description ?? string.Empty);
}
}
推荐阅读
- c# - 如何在 .NET 2 项目中使用 .NET 4.7 程序集?
- apache-superset - Apache SuperSet 非常慢
- asp.net-core - Autofac注册IHttpContextAccessor
- java - 使用 Gson 使用默认值序列化 protobuf
- javascript - 使用javascript以表格形式打印动态json数据
- html - 如何在 html css 中添加印地文字体(英文字母到印地文字母,如 (kaise ho =>कैसे हो))
- react-native - Expo发布渠道和项目文件夹
- wordpress - htaccess 将子目录重定向到另一个子目录
- python-3.x - 使用 Python 进行 Web 抓取,需要登录才能查看输出
- google-cloud-firestore - Firestore 规则 - 与 where 一起使用