Search code examples
c#telerik-gridtelerik-mvccode-reuse

Kendo MVC C# is it possible to have generic fields in some kind of template to include easily in all grids?


So we have about 90 grids. In an attempt to standardize column widths, etc, I was considering pulling out the audit trail fields into some kind of base class but i'm not sure how possible this is. We have six fields for create date, last change date, and delete date and who did it, and they are at the end of every grid. Is there some kind of way to generate them in one common place and include them?


Solution

  • Yes

    To solve this, you will need to write an extension method to the GridBuilder class.

    Because you want to add your audit trail columns to the end, you would employ the same strategy that is found in this solution and this solution:

    1. Write extention method .AddAuditTrailColumns()
    2. Define your Grid Columns that are non audit trail
    3. Call .AddAuditTrailColumns()

    It would look something like:

    public static class Extensions
    {
        public static GridBuilder<T> AddAuditTrailColumns<T>(this GridBuilder<T> builder) where T: class
        {
            //add audit trail columns
            builder.Columns(columns =>
            {
                columns.Bound("CreateDate").Filterable(false);
                columns.Bound("CreatedBy");
                columns.Bound("LastChangeDate");
                columns.Bound("LastChangedBy");
                columns.Bound("DeleteDate");
                columns.Bound("DeletedBy");
            });
            return builder;
        }
    }
    

    You could use lambdas if all your grids use the same base class. In the template:

    @(Html.Kendo.Grid<Product>("Grid74")
        .BindTo(Model)
        .Columns(columns =>
               {
                   columns.Bound(p => p.Name);
                   columns.Bound(p => p.Description);
               })
       .AddAuditTrailColumns()
    )
    

    I applaud your instinct reusing as much as possible. The people maintaining these 90 grids will have an easier job and you will do less work in the end. WIN-WIN.