Get DisplayName Attribute without using LabelFor Helper in asp.net MVC

后端 未结 3 2052
说谎
说谎 2020-11-29 19:47

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 app

相关标签:
3条回答
  • 2020-11-29 20:09

    In my opinion you should use a string as a result type because otherwise you skip the encoding mechanism. Another point is that you need the DisplayName in some cases as a string (i.e. populate the columns in a WebGrid class).

    0 讨论(0)
  • 2020-11-29 20:11

    You should try new existing function :

    <% Html.DisplayNameFor(m => m.YourProperty) %>
    
    0 讨论(0)
  • 2020-11-29 20:29
    <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);
        }
    }
    

    And then:

    <p>
        <%: Html.GetDisplayName(x => x.SomeProperty) %>
    </p>
    
    0 讨论(0)
提交回复
热议问题