How can I use the ShortName property of the Displa

2020-07-17 14:13发布

I see the DisplayAttribute has a ShortName property, but I see no Html.ShortName helper. How can I get to use this short name for my table column headings? Do I have to write my own helper?

2条回答
【Aperson】
2楼-- · 2020-07-17 14:45

For me the accepted answer didn't help much because my view model was defined as an IEnumerable:

@model IEnumerable<Document>

And so I needed a DisplayShortNameFor version of the existing extension method:

public static MvcHtmlString DisplayNameFor<TModel, TValue>(this HtmlHelper<IEnumerable<TModel>> html, Expression<Func<TModel, TValue>> expression);

I was able to find one in here:

public static string DisplayShortNameFor<TModel, TValue>(this global::System.Web.Mvc.HtmlHelper<global::System.Collections.Generic.IEnumerable<TModel>> t, global::System.Linq.Expressions.Expression<global::System.Func<TModel,TValue>> exp)
{
    CustomAttributeNamedArgument? DisplayName = null;
    var prop = exp.Body as MemberExpression;
    if (prop != null)
    {
        var DisplayAttrib = (from c in prop.Member.GetCustomAttributesData()
                             where c.AttributeType == typeof(DisplayAttribute)
                             select c).FirstOrDefault();
        if(DisplayAttrib != null)
            DisplayName = DisplayAttrib.NamedArguments.Where(d => d.MemberName == "ShortName").FirstOrDefault();
    }
    return DisplayName.HasValue ? DisplayName.Value.TypedValue.Value.ToString() : "";
}

Not sure if it is the best approach but it worked fine for me.

查看更多
戒情不戒烟
3楼-- · 2020-07-17 14:49

You could write your own helper :

Something like

public static IHtmlString ShortLabelFor<TModel, TValue>(this HtmlHelper<TModel> helper, Expression<Func<TModel, TValue>> expression) {
   var metadata = ModelMetadata.FromLambdaExpression(expression, helper.ViewData);
   var content = metadata.ShortDisplayName?? metadata.DisplayName ?? /*something else*/ ?? string.Empty;
   return new HtmlString(content);
}

But, from msdn :

The short display name can be used in a tooltip or in other display contexts such as the title of tabular list views where the complete display name might not fit. For example, in MVC, this name is used in tables where the columns are not wide enough to display the complete field name. If this field is null, DisplayName should be used.

So it looks like it should be automatic (when no room enough), but... untested here. Sounds like it should work with @Html.LabelFor in this way.

查看更多
登录 后发表回答