MVC的WebGrid动态列 [英] MVC WebGrid Dynamic Columns
问题描述
所以我有一个包含元数据项的列表是每个用户自定义的。模型
So I have a model that contains a list of meta data items that is customizable per user.
public class MyModel {
public int ID { get; set; }
public String Name { get; set; }
public DateTime Created { get; set; }
// Need to diplay each as a column
public List<MetaData> Data { get; set; }
}
public class MetaData {
public int ID { get; set; }
public String Name { get; set; }
public String Label { get; set; }
public String Value { get; set; }
}
有关为MyModel每一个元数据项,我需要一列添加到其名称作为列名,标签作为标题,并为每个输出为MyModel价值的WebGrid
For each metadata item on MyModel I need to add a column to the WebGrid that has the name as the column name, the label as the header, and the value outputted for each MyModel.
@{
WebGrid grid = new WebGrid(source: Model, rowsPerPage: 5, canPage: true);
List<WebGridColumn> cols = new List<WebGridColumn>();
cols.Add(grid.Column("Name", "Name"));
cols.Add(grid.Column("Created"));
for (int i = 0; i < Model.FirstOrDefault().Data.Count; i++)
{
cols.Add(grid.Column(Model.FirstOrDefault().Data[i].Name, Model.FirstOrDefault().Data[i].Label,
format: item => @<text>@item.Data[i].Value</text>
));
}
}
@grid.GetHtml(
tableStyle: "table",
htmlAttributes: new { id = "MyGrid" },
columns: cols)
的元数据列都MyModels之间共享所以每个人会不会有新的一组列。的名称和标号将在整个不同为MyModel的相同。如果有人可以帮助,这将是更AP preciated。
The metadata columns are shared between all MyModels so each one will not have a new set of columns. The name and label will be the same throughout the different MyModel's. If anyone can help, it would be much appreciated.
推荐答案
在的lambda语法过于复杂,你可以切换到使用 Html.Raw
。此外,它似乎有一种修改封随着指数的问题,因为运行时尝试使用最后的值 I
- 你可以通过本地复印件(环内)解决这个问题我
。这对我的作品:
When the lambda syntax gets too complex, you can switch to using Html.Raw
. Also, it seems you have a sort of "modified closure" issue with the index, because the runtime is trying to use the last value of i
-- you can fix this by making a "local" (inside the loop) copy of i
. This works for me:
for (int i = 0; i < Model.First().Data.Count; i++)
{
int local = i;
cols.Add(grid.Column(Model.First().Data[i].Name, Model.First().Data[i].Label,
format: item => Html.Raw("<text>" + item.Data[local].Value + "</text>")
));
}
修改
在格式拉姆达黑客......这显然也适用:
Hacking at the "format" lambda ... this also apparently works:
format: item => @item.Data[local].Value
这篇关于MVC的WebGrid动态列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!