How can I use DisplayName data annotations for column headers in WebGrid?

妖精的绣舞 提交于 2019-12-03 02:12:52

Ugly as hell but it could work:

grid.Column(
    "CarName", 
    ModelMetadata.FromLambdaExpression(
        car => car.CarName, 
        new ViewDataDictionary<Car>(new Car())
    ).DisplayName
)

The problem is that the WebGrid helper is entirely based on dynamic data, absolutely no strong typing and that's one of the reasons why I hate it. The WebMatrix team at Microsoft must be real fans of the C# 4.0 dynamic feature as their entire API takes only weakly typed objects :-)

MvcContrib Grid is much better.

I have created a helper method like this:

public static string GetDisplayName<TModel, TProperty>(this HtmlHelper<TModel> html, Expression<Func<TModel, TProperty>> property)
{
    return GetDisplay(property);
}

public static string GetDisplayName<TModel, TProperty>(this HtmlHelper<IEnumerable<TModel>> html, Expression<Func<TModel, TProperty>> property)
{
    return GetDisplay(property);
}

private static string GetDisplay<M,P>(Expression<Func<M,P>> property)
{
    var propertyExp = (MemberExpression)property.Body;
    var member = propertyExp.Member;
    var disp = (DisplayAttribute)member.GetCustomAttribute(typeof(DisplayAttribute));
    if (disp == null)
    {
        return member.Name;
    }
    return disp.Name;
}

And used it like this:

new WebGridColumn { Header = Html.GetDisplayName(t=>t.Title), ColumnName = nameof(DataModel.Title), CanSort=true }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!