MVC3 WebGrid - 动态创建列(foreach?)

时间:2011-11-21 08:51:37

标签: asp.net-mvc-3 webgrid

我想创建一个WebGrid,其中包含基于集合的列,例如List。像这样的东西(显然不起作用):

@grid.GetHtml(
  columns: grid.Columns(
    @foreach (var column in Model.ListOfColumns) {
       grid.Column(column.Name, column.Title);
    }
  )
)          

任何聪明的想法?

3 个答案:

答案 0 :(得分:8)

你可以像下面一样ViewBag。

控制器:

        List<WebGridColumn> columns = new List<WebGridColumn>();
        columns.Add(new WebGridColumn() { ColumnName = "Id", Header = "Id" });
        columns.Add(new WebGridColumn() { ColumnName = "Name", Header = "Name" });
        columns.Add(new WebGridColumn() { ColumnName = "Location", Header = "Location" });
        columns.Add(new WebGridColumn() { Format = (item) => { return new HtmlString(string.Format("<a href= {0}>View</a>", Url.Action("Edit", "Edit", new { Id = item.Id }))); } });
        ViewBag.Columns = columns;

查看:

   @grid.GetHtml(tableStyle: "ui-widget ui-widget-content",
                      headerStyle: "ui-widget-header",
                      columns: ViewBag.Columns
                     )

答案 1 :(得分:4)

试试这个:

@{
    List<WebGridColumn> cols = new List<WebGridColumn>();
    foreach(var column in Model.ListOfColumns)
    {
        cols.Add(grid.Column(column.Name, column.Title));
    }
}

@grid.GetHtml(
    columns: cols
)

答案 2 :(得分:0)

您可以使用辅助方法

public static class GridExtensions
{
    public static WebGridColumn[] DynamicColumns(
        this HtmlHelper htmlHelper,
        WebGrid grid
    )
    {
        var columns = new List<WebGridColumn>();

        columns.Add(grid.Column("Property1", "Header", style: "record"));
        columns.Add(grid.Column("Property2", "Header", style: "record"));
       columns.Add(grid.Column("Actions", format: (item) => { return new HtmlString(string.Format("<a target='_blank' href= {0}>Edit </a>", "/Edit/" + item.Id) + string.Format("<a target='_blank' href= {0}> Delete</a>", "/Delete/" + item.Id)); }));
        return columns.ToArray();
    }

用法:

@{
    var grid = new WebGrid(Model);
}
@grid.GetHtml(columns: grid.Columns(Html.DynamicColumns(grid)))