2

I want to create a WebGrid with columns based on a collection, such as List. Something like this (which obviously doesn't work):

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

Any clever ideas?

pfeds
  • 2,183
  • 4
  • 32
  • 48

3 Answers3

8

You could ViewBag it like below.

Controller:

        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;

View:

   @grid.GetHtml(tableStyle: "ui-widget ui-widget-content",
                      headerStyle: "ui-widget-header",
                      columns: ViewBag.Columns
                     )
Ringo Long
  • 104
  • 2
  • 4
  • I managed to get the code working previously using a foreach loop but needed to assign each column to a local variable before adding to the columns collection. The local variable was necessary to resolve a lambda "access to modified exposure" issue. Your solution is neater, thanks. – pfeds Dec 07 '12 at 01:39
4

Try this:

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

@grid.GetHtml(
    columns: cols
)
Billy Jo
  • 1,326
  • 19
  • 32
0

You could use helper method

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();
    }

Usage:

@{
    var grid = new WebGrid(Model);
}
@grid.GetHtml(columns: grid.Columns(Html.DynamicColumns(grid)))
Moe
  • 47
  • 2
  • 8