如何解决如何使用 ShortName 属性?
我的模型中有一个 ShortName 属性(预计是“用于网格列标签”)
[MaxLength(256)]
[display(Name = "Description",ShortName = "Desc.")]
public string Description { get; set; }
我在列的网格标题中使用了 displayFor
,如文档所示。
<thead>
<tr>
<th>
@Html.displayNameFor(model => model.Description)
</th>
但是,我在列标题中看到了“描述”,而不是“描述”。正如预期的那样。
我尝试做的 MS 确实for DisplayName:
public static class HtmlHelperdisplayNameExtensions
{
public static string displayShortNameForModel(this IHtmlHelper htmlHelper)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
return htmlHelper.displayShortNameForModel();
}
public static string displayShortNameFor<TModelItem,TResult>(
this IHtmlHelper<IEnumerable<TModelItem>> htmlHelper,Expression<Func<TModelItem,TResult>> expression)
{
if (htmlHelper == null)
{
throw new ArgumentNullException(nameof(htmlHelper));
}
if (expression == null)
{
throw new ArgumentNullException(nameof(expression));
}
// << ???? >>>>>>>
return htmlHelper.displayShortNameForInnerType(expression); // ??????
// << ???? >>>>>>>
// << ???? >>>>>>>
}
}
不幸的是,displayShortNameForInnerType
不存在
解决方法
据我所知,没有内置的 html 扩展方法可以显示短名称。
如果你想使用它,你只能自己创建扩展方法。另外,根据source codes,你还可以发现asp.net核心团队也返回了HtmlString来渲染视图。
但是如果我们想使用扩展方法,我们不能使用DI注入可以直接获取显示名称属性的ModelExpressionProvider。我们应该自己写逻辑。
更多细节,您可以参考以下代码:
public static class HtmlExtensions
{
public static IHtmlContent DescriptionFor<TModel,TValue>(this IHtmlHelper<TModel> html,Expression<Func<TModel,TValue>> expression)
{
var propertyName = ((PropertyInfo)((MemberExpression)expression.Body).Member).Name;
var attribute = ((PropertyInfo)((MemberExpression)expression.Body).Member).CustomAttributes.Where(x=>x.AttributeType == typeof(DisplayAttribute));
var shortname = attribute.FirstOrDefault().NamedArguments.Where(x => x.MemberName == "ShortName").FirstOrDefault().TypedValue;
return new HtmlString(string.Format(@"<span>{0}</span>",shortname));
}
}
用法:
@Html.DescriptionFor(x => x.Description)
结果:
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。