How to create a webgrid with dynamic columns?

1

I saw several examples using WebGrid but all with the number of fixed columns. My data source will return a dynamic list, that is, sometimes it returns 5 columns and then it can return 6 colunass, how to do?

    
asked by anonymous 09.05.2017 / 20:56

1 answer

1

Something like this:

@model IEnumerable<dynamic>

@{
    WebGrid grid = new WebGrid(source: Model, rowsPerPage: 5, canPage: true);

    List<WebGridColumn> cols = new List<WebGridColumn>();
    cols.Add(grid.Column("ColunaManual", "Coluna Manual"));
    foreach (Dictionary<string, string> linha in Model.Select(m => m.ToPropertyDictionary()))
    {
        cols.Add(grid.Column(linha.Key, linha.Key, 
            format: item => Html.Raw("<text>" + linha.Value + "</text>")
        ));
    }
}

ToPropertyDictionary() is here:

public static class DictionaryExtensions 
{
    public static Dictionary<string, string> ToPropertyDictionary(this object obj)
    {
        var dictionary = new Dictionary<string, string>();
        foreach (var propertyInfo in obj.GetType().GetProperties())
            if (propertyInfo.CanRead && propertyInfo.GetIndexParameters().Length == 0)
                dictionary[propertyInfo.Name] = (propertyInfo.GetValue(obj, null) ?? "").ToString();
        return dictionary;
    }
}
    
09.05.2017 / 22:56