我有一个模型和一个字段……等等。这很简单。但是,我需要从我的 View 中获取字段中的“描述”属性和您的“名称”属性。使用 @Html... 很明显,可以使用“DisplayNameFor”返回此值。但是,如何获得“Description”属性呢?没有像@Html.DisplayDescription 这样的助手?有可能得到这个吗?
[Column("abc")]
[Display(Description = "The Description", GroupName = "The Group", Name = "The Name")]
public string field { get; set; }
谢谢你的帮助。
对不起,英语不好。 ;)
您可以从元数据中获取它:
@model MyViewModel
@{
var description = ModelMetadata.FromLambdaExpression<MyViewModel, string>(x => x.field, ViewData).Description;
}
@description
或者,如果您像我一样发现在 View 中编写的这段代码非常糟糕,您可以将其封装在可重用的帮助程序中:
public static class HtmlExtensions
{
public static IHtmlString DescriptionFor<TModel, TValue>(
this HtmlHelper<TModel> html,
Expression<Func<TModel, TValue>> expression
)
{
var metadata = ModelMetadata.FromLambdaExpression(expression, html.ViewData);
var description = metadata.Description;
return new HtmlString(description);
}
}
所以在你看来你可以这样使用:
@model MyViewModel
@Html.DescriptionFor(x => x.field)