Asp.net
如何為 WebGrid 中的列標題使用 DisplayName 數據註釋?
我有一個 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 中的列標題文本(?????)。有誰知道這是如何實現的?
提前致謝!
醜得要命,但它可以工作:
grid.Column( "CarName", ModelMetadata.FromLambdaExpression( car => car.CarName, new ViewDataDictionary<Car>(new Car()) ).DisplayName )問題是 WebGrid 助手完全基於動態數據,絕對沒有強類型,這也是我討厭它的原因之一。Microsoft 的 WebMatrix 團隊一定是 C# 4.0 動態特性的忠實擁護者,因為他們的整個 API 只接受弱類型對象 :-)
MvcContrib Grid要好得多。
我創建了一個這樣的輔助方法:
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 }