小编典典

如何显示DisplayAttribute.Description属性值?

c#

我有一个模型类,具有这样的属性:

[Display(Name = "Phone", Description="Hello World!")]
public string Phone1 { get; set; }

在我的视图中显示标签并渲染文本框以供输入非常简单:

@Html.LabelFor(model => model.Organization.Phone1)
@Html.EditorFor(model => model.Organization.Phone1)
@Html.ValidationMessageFor(model => model.Organization.Phone1)

但是,如何渲染Description注释属性的值,即“ Hello World!”?


阅读 621

收藏
2020-05-19

共1个答案

小编典典

我最终得到了这样的帮手:

using System;
using System.Linq.Expressions;
using System.Web.Mvc;

public static class MvcHtmlHelpers
{
    public static MvcHtmlString DescriptionFor<TModel, TValue>(this HtmlHelper<TModel> self, Expression<Func<TModel, TValue>> expression)
    {
        var metadata = ModelMetadata.FromLambdaExpression(expression, self.ViewData);
        var description = metadata.Description;

        return MvcHtmlString.Create(string.Format(@"<span>{0}</span>", description));
    }
}

感谢那些引导我朝着正确方向前进的人。:)

2020-05-19