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

后端 未结 2 1863
不思量自难忘°
不思量自难忘° 2021-02-05 16:02

I have a Car class that I\'m trying to display in an MVC 3 view using the WebGrid helper. Below are the Car and it\'s metadata class.

Car class:

[Meta         


        
相关标签:
2条回答
  • 2021-02-05 16:09

    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 }
    
    0 讨论(0)
  • 2021-02-05 16:19

    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.

    0 讨论(0)
提交回复
热议问题