在 asp.net MVC 中不使用 LabelFor Helper 获取 DisplayName 属性 [英] Get DisplayName Attribute without using LabelFor Helper in asp.net MVC
本文介绍了在 asp.net MVC 中不使用 LabelFor Helper 获取 DisplayName 属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
检索模型中项目的显示名称属性的最佳方法是什么?我看到很多人都使用 LabelFor 助手来处理所有事情,但是如果我只想列出数据,则标签不合适.如果我只想将其打印出来,例如一个段落,是否有一种简单的方法来获取名称属性?
What is the best way to retrieve the display name attribute for an item in your model? I see a lot of people using the LabelFor helper for everything, but a label isn't appropriate if I just want to list the data out. Is there an easy way just get the Name Attribute if I just want to print it out in, say a paragraph?
推荐答案
<p>
<%= Html.Encode(
ModelMetadata.FromLambdaExpression<YourViewModel, string>(
x => x.SomeProperty, ViewData).DisplayName
) %>
<p>
显然,为了避免意大利面条式代码,编写一个帮助程序总是一个好主意:
Obviously in order to avoid the spaghetti code it is always a good idea to write a helper:
public static class HtmlExtensions
{
public static MvcHtmlString GetDisplayName<TModel, TProperty>(
this HtmlHelper<TModel> htmlHelper,
Expression<Func<TModel, TProperty>> expression
)
{
var metaData = ModelMetadata.FromLambdaExpression<TModel, TProperty>(expression, htmlHelper.ViewData);
string value = metaData.DisplayName ?? (metaData.PropertyName ?? ExpressionHelper.GetExpressionText(expression));
return MvcHtmlString.Create(value);
}
}
然后:
<p>
<%: Html.GetDisplayName(x => x.SomeProperty) %>
</p>
这篇关于在 asp.net MVC 中不使用 LabelFor Helper 获取 DisplayName 属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文