gpt4 book ai didi

c# - PropertyInfo 到 Expression>

转载 作者:行者123 更新时间:2023-11-30 16:12:22 25 4
gpt4 key购买 nike

我想为 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;}

}

最佳答案

你可以这样试试:

        var properties = typeof (TModel).GetProperties();
foreach (PropertyInfo info in properties)
{
ParameterExpression p1 = Expression.Parameter(typeof(TModel), "m");
ParameterExpression p2 = Expression.Parameter(info.PropertyType, "m."+info.Name);
Expression<Func<TModel, dynamic>> exResult = Expression.Lambda<Func<TModel, dynamic>>(p1, p2);

helper.DisplayFor(exResult);
}

抱歉,花了一些时间。不得不做一些其他的工作。

关于c# - PropertyInfo 到 Expression<Func<TModel, TProperty>>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23060850/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com