Search code examples
asp.net-mvckendo-uikendo-gridviewbag

How to conditionally group or not group KendoUI grid based on Viewbag value


I need to pass a column name or the value 'none' to my kendo grid to conditionally group it based on the value of a Viewbag element. When I pass the column name in it groups as expected. My issue is to not do grouping if the value 'none' is passed in. the code which I have is:

@(Html.Kendo().Grid<dynamic>()
    .Name("exportGrid")
    .DataSource(dataSource =>
    {
        dataSource.Ajax()
        .Read("ReadGrid", "Report", new { id = Model.Inquiry_ID })
        .Group(grp => grp.Add(ViewBag.groupBy, typeof(string)))
        .Model(m =>
        {
            // Add the fields to the dynamic model
            foreach (var field in Fields)
            {
                switch (field.DATA_TYP_NUM)
                {
                    case 1: m.Field(field.INTERNL_NME, typeof(string)); break;
                    case 2: m.Field(field.INTERNL_NME, typeof(double?)); break;
                    case 3: m.Field(field.INTERNL_NME, typeof(double?)); break;
                    case 4: m.Field(field.INTERNL_NME, typeof(DateTime?)); break;
                }
            }
        })

        .ServerOperation(true);
    })
    .Groupable()
    .Filterable()
    .Sortable()
    .ColumnMenu()
    .Events(e => e.DataBound("onDataBound"))
    .Resizable(resize => resize.Columns(true))
    .Columns(columns =>

As I said - this works fine but I need a way to exclude the .Group(....) clause when Viewbag.groupBy == "none"


Solution

  • Just add the condition in the Group option :

    .Group(grp => {
        if(ViewBag.groupBy != "none") {
            grp.Add(ViewBag.groupBy, typeof(string));
        }
    })