我想为ASP.NET和Razor创建一种WebGrid 2.0。PropertyInfo to Expression <Func <TModel,TProperty >>
定义ModelClass(TData)时,WebGrid应自行为表创建HTML。
TData的属性应该通过反射(typeof(TData).GetProperties)读取。属性的属性应该定义一些css和html样式或甚至一些数据(DisplayNameAttribute => ColumnHeader)。
现在我来到了这一点,当我想调用htmlHelper.DisplayFor(... propertyInfoToExpression ...)来呈现数据内容。
我怎么能调用DisplayFor,当我只有数据(行)/模型和propertyInfo?
的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;}
}
什么?你能用样本代码来描述它吗(对于模式,以及所需呼叫结构的片段)。可能很容易找出解决方案。通常用表达式可以解决事情,而无需处理PropertyInfo。 – Dbl
我添加了一些示例代码。 – Tobias
我不认为你的班级概念是正确的吗?我想你想这样调用它(假设你传递给你的视图的模型是UserModel类型的:@ Html.WebGridFor(x => x)?制作它的列表将是毫无意义的 我想你'重新修改你的代码 – Dbl