How to create a webgrid with dynamic columns?

Asked

Viewed 242 times

1

I saw several examples using Webgrid but all with the number of fixed columns. My data source will return a dynamic list, IE, either returns 5 columns and then can return 6 columns, how to do ?

1 answer

1


Something like that:

@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;
    }
}
  • got it, the Modelo is converted into a type Dictionary, but now I realized the following: the data with the dynamic amount of attributes will come from a Procedure and how to make a Model to reflect this dynamic amount of attributes ? Is there ? , for example in the context class I will have to do something like this: modelBuilder.Entity<Documento>().MapToStoredProcedures();. The data comes from one to the previous due to a Pivot function that is used in that process.

  • Ask another question, please.

  • Thank you @Cigano Morrison Mendez I created a new question [link] https://answall.com/questions/205530/attribute-din%C3%A2mico-de-um-modelo-entidade [link] .

Browser other questions tagged

You are not signed in. Login or sign up in order to post.