我想为ASP.NET和Razor创建一种WebGrid 2.0。

定义ModelClass(TData),WebGrid应自行为表创建HTML。

TData的属性应通过反射(typeof(TData).GetProperties)读取。属性的属性应定义一些CSS和HTML样式,甚至定义一些数据(DisplayNameAttribute => ColumnHeader)。

现在,我想调用htmlHelper.DisplayFor(... propertyInfoToExpression ...)呈现数据内容的时候到了。

当我仅获得数据(行)/模型和propertyInfo时,如何调用DisplayFor?



WebGrid类:

public class TableModel<TData>{

     private readonly IList<TData> _rows;
     private readonly IList<TableColumn<TData>> _columns = new List<TableColumn<TData>>();


     public TableModel(IList<TData> rows) {
        _rows = rows;

        PropertyInfo[] propertyInfos = typeof(TData).GetProperties();
        foreach (PropertyInfo property in propertyInfos) {
            if (!Attribute.IsDefined(property, typeof(NoColumnAttribute))) {
                _columns.Add(new TableColumn<TData>(property));
            }
        }

    }

    private MvcHtmlString GetCellHtml(HtmlHelper<TData> helper, TableColumn column, TData dataRow){

         TagBuilder cellTagBuilder = new TagBuilder("td");
         cellTagBuilder.InnerHtml = helper.DisplayFor(...propertyInfoToExpression...)

    }

    public MvcHtmlString ToHtml(HtmlHelper helper){
         TagBuilder tableTagBuilder = new TagBuilder("table");
         TagBuilder headTagBuilder = new TagBuilder("thead");
         TagBuilder bodyTagBuilder = new TagBuilder("tbody");

         ...
         return new MvcHtmlString(tableTagBuilder);
    }
}


TData的示例类正好抓住了这个主意:

public class UserModel{

      [NoColumnAttribute]
      public int Id{get;set;}

      [CssClass("name")]
      public string Firstname {get;set;}

      [CssClass("name")]
      public string Lastname{get;set;}

      [CssClass("mail")]
      public string Mail{get;set;}

      [CssClass("phone")]
      public string Phone{get;set;}

}

最佳答案

你有没有尝试过...

private MvcHtmlString GetCellHtml(HtmlHelper<TData> helper, TableColumn column, TData dataRow){

     TagBuilder cellTagBuilder = new TagBuilder("td");
     cellTagBuilder.InnerHtml = helper.Display(column.PropertyInfo.Name, dataRow);
     ...
}


...?

如果仅对方法DisplayFor需要GetCellHtml,则实际上不需要从PropertyInfo构建表达式。

08-05 14:04