【问题标题】:How can I use DisplayName data annotations for column headers in WebGrid?如何为 WebGrid 中的列标题使用 DisplayName 数据注释?
【发布时间】:2011-07-12 03:59:16
【问题描述】:

我有一个 Car 类,我试图使用 WebGrid 帮助器在 MVC 3 视图中显示它。下面是 Car 及其元数据类。

汽车类:

[MetadataType(typeof(CarMetadata))]
public partial class Car
{
    // car implementation
}

汽车元数据类:

public class CarMetadata
{        
    [DisplayName("Car Name")]
    [StringLength(100, ErrorMessageResourceType = typeof(ValidationText), ErrorMessageResourceName="CarNameDescriptionLength")]
    [Required]
    public string CarName { get; set; }    
}

查看内容:

@model List<Car>
...
var grid = new WebGrid(Model, canPage: true, rowsPerPage: 10);
grid.Pager(WebGridPagerModes.NextPrevious);

@grid.GetHtml(
    htmlAttributes: new { id = "grid" },
    columns: grid.Columns(
        grid.Column("CarName", ?????)
    ));

目标:我想弄清楚如何将 DisplayName 数据注释用作 WebGrid 中的列标题文本 (?????)。有谁知道这是怎么实现的吗?

提前致谢!

【问题讨论】:

    标签: asp.net asp.net-mvc-3 data-annotations webgrid


    【解决方案1】:

    丑得要命,但它可以工作:

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

    问题在于 WebGrid 助手完全基于动态数据,绝对没有强类型,这也是我讨厌它的原因之一。 Microsoft 的 WebMatrix 团队一定是 C# 4.0 动态特性的忠实拥护者,因为他们的整个 API 只接受弱类型对象 :-)

    MvcContrib Grid 好多了。

    【讨论】:

    • 感谢您的回复。 MvcContrib 是否与 DataAnnotations 一起使用?
    • @80bower,是的,它是强类型的,您可以轻松实现。
    • 感谢您的意见。我将研究使用 MvcContrib。是的,您的解决方案有效,是的,它很丑陋。 :)
    • 不幸的是,MvcContrib Grid 不再真正维护了(因为最后一次更新是从 2011 年开始的)
    【解决方案2】:

    我创建了一个这样的辅助方法:

    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;
    }
    

    并像这样使用它:

    new WebGridColumn { Header = Html.GetDisplayName(t=>t.Title), ColumnName = nameof(DataModel.Title), CanSort=true }
    

    【讨论】:

      猜你喜欢
      • 2011-09-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-08-17
      • 1970-01-01
      • 2014-04-05
      相关资源
      最近更新 更多