This is a migrated thread and some comments may be shown as answers.

[Solved] How to avoid code duplication when creating a grid?

1 Answer 89 Views
Grid
This is a migrated thread and some comments may be shown as answers.
This question is locked. New answers and comments are not allowed.
Pavels
Top achievements
Rank 1
Pavels asked on 28 Nov 2011, 04:34 PM
Hi,

I've got a base class NamedObject and many classes that descend from it. I need to display objects of descendent classes in the grid, each descendant class has got its own specific set of "columns" (properties). Please can you advise how I can tell the Grid which class type to use to automatically generate the columns? If I just pass-in an IEnumerable<NamedObject> then the grid gives me columns of NamedObject, but I need to display columns of the actual type of the data that I'm passing into the grid. Is there a way to achieve this without duplicating the below code block for every descendant class type?

Thanks.

Pavels.

-------------------------------------
Code Block:
-------------------------------------

@{ Html.Telerik().Grid((IEnumerable<NamedObject>)ViewData["ModuleEntityObjects"])
       .Name("MainGrid")
       .HtmlAttributes(new { style = "float: left" })
       .Columns(columns => { columns.AutoGenerate(true); columns.Command(commands => { commands.Edit(); commands.Delete(); }); })
       .ToolBar(commands => commands.Insert())
       .DataKeys(keys => keys.Add(f => f.ID))
       .DataBinding(dataBinding => dataBinding.Ajax()
           .Select("SelectObject", ModuleSystemName)
           .Insert("InsertObject", ModuleSystemName)
           .Update("ModifyObject", ModuleSystemName)
           .Delete("DeleteObject", ModuleSystemName))
       .Sortable(sorting => sorting
           .OrderBy(order => order.Add(o => o.Name))
           .Enabled(true))
       .Filterable(filtering => filtering.Enabled(true))
       .Resizable(resizing => resizing.Columns(true))
       .Reorderable(reorder => reorder.Columns(true))
       .Render();
}

1 Answer, 1 is accepted

Sort by
0
Tony
Top achievements
Rank 1
answered on 01 Dec 2011, 04:01 AM
I haven't tries what you're working with, but in the worst case scenario, you can use the gridcolumoptions from the controller and pass that to the grid. At least you'd only have to do it in code once - save it to helper. It's not auto generated but at least only built once. You could also do a little reflection action and make a generic one.
Tags
Grid
Asked by
Pavels
Top achievements
Rank 1
Answers by
Tony
Top achievements
Rank 1
Share this question
or