Sunteți pe pagina 1din 1114

Essential Studio 2014 Volume 1 - v. 12.1.0.

43
Essential Grid for ASP.NET MVC Classic
Essential Grid for ASP.NET MVC Classic

Contents

1 Overview 18
1.1 Introduction to Essential Grid for ASP.NET MVC ................................................................. 18
1.2 Prerequisites and Compatibility ........................................................................................... 20
1.3 Documentation .................................................................................................................... 21

2 Installation and Deployment 23


2.1 Deployment Requirements .................................................................................................. 23
2.1.1 Default Deployment Pattern .................................................................................... 24
2.1.2 Fast Deployment Pattern ........................................................................................ 24
2.1.3 DLL ........................................................................................................................ 24
2.2 Samples and Location ......................................................................................................... 25

3 Getting Started 29
3.1 Getting Started with the Syncfusion MVC Grid ..................................................................... 29
3.1.1 Syncfusion Utilites .................................................................................................. 29
3.1.1.1 Project Template Utility............................................................................... 29
3.1.1.1.1 Creating an MVC4 Razor application with the
Syncfusion Project Template.......................................................... 29
3.1.1.2 Project Migration Utility ............................................................................... 33
3.1.1.2.1 Converting an existing MVC application to a
Syncfusion MVC application........................................................... 33
3.1.2 Adding Grid to the project ....................................................................................... 35

4 Concepts and Features 39


4.1 Action Modes ...................................................................................................................... 39
4.1.1 Server Mode ........................................................................................................... 40
4.1.1.1 Through GridBuilder ................................................................................... 40
4.1.1.2 Through GridPropertiesModel..................................................................... 42
4.1.2 JSON Mode ............................................................................................................ 44
4.1.2.1 Through GridBuilder ................................................................................... 44
4.1.2.2 Through GridPropertiesModel..................................................................... 46
4.2 Data Binding ....................................................................................................................... 48
4.2.1 LINQ to SQL Data Source....................................................................................... 49

© 2014 Syncfusion. All rights reserved. 2 | Page


Essential Grid for ASP.NET MVC Classic

4.2.1.1 Through GridBuilder ................................................................................... 49


4.2.1.2 Through GridPropertiesModel..................................................................... 51
4.2.2 ADO.NET Entity Model Data Source ....................................................................... 53
4.2.2.1 Through GridBuilder ................................................................................... 54
4.2.2.2 Through GridPropertiesModel..................................................................... 56
4.2.3 Generic Collections ................................................................................................. 58
4.2.3.1 Through GridBuilder ................................................................................... 58
4.2.3.2 Through GridPropertiesModel..................................................................... 60
4.2.4 Unbound Column .................................................................................................... 62
4.2.4.1 Through GridBuilder ................................................................................... 63
4.2.4.2 Through GridPropertiesModel..................................................................... 66
4.2.5 Data binding support for drop-down lists in columns ................................................ 68
4.2.5.1 Properties .................................................................................................. 69
4.2.5.2 Methods ..................................................................................................... 69
4.2.5.3 Data binding support .................................................................................. 70
4.2.5.3.1 Bind drop-down data using the Enumerable method.................. 70
4.2.5.3.2 Bind drop-down data using Action Mapper ................................ 87
4.2.5.3.3 Bind drop-down data using Array ............................................ 105
4.2.6 Auto-Generated Columns ..................................................................................... 114
4.2.6.1 Through GridBuilder ................................................................................. 114
4.2.6.2 Through GridPropertiesModel................................................................... 115
4.2.7 Custom Binding .................................................................................................... 116
4.2.7.1 Through GridBuilder ................................................................................. 117
4.2.7.2 Through GridPropertiesModel................................................................... 122
4.2.8 Web Service Data Binding .................................................................................... 127
4.2.8.1 Through GridBuilder ................................................................................. 127
4.2.8.2 Through GridPropertiesModel................................................................... 131
4.2.9 Dynamic Data Binding .......................................................................................... 136
4.2.9.1 Dynamically Bind Data to Grid without mapping to column names ............ 136
4.2.9.1.1 Through GridBuilder ................................................................ 136
4.2.9.1.2 Through GridPropertiesModel ................................................. 138
4.2.9.2 Dynamically Bind data with mapping the column name as string ............... 139
4.2.9.2.1 Through GridBuilder ................................................................ 140
4.2.9.2.2 Through GridPropertiesModel ................................................. 142
4.2.10 DataTable Support................................................................................................ 143

© 2014 Syncfusion. All rights reserved. 3 | Page


Essential Grid for ASP.NET MVC Classic

4.2.10.1 Through GridBuilder..................................................................... 144


4.2.10.2 Through GridPropertiesModel ...................................................... 147
4.2.11 JSON Binding to MVC Grid and Monitoring Changes with Knockout.js .................. 149
4.2.11.1 Grid preparation ........................................................................... 149
4.2.11.2 Knockout’s ViewModel ................................................................. 150
4.2.11.3 Integrating the Grid and Knockout’s ViewModel ........................... 151
4.2.11.4 Playing with the JSON Collection ................................................. 152
4.3 Paging............................................................................................................................... 154
4.3.1 Server Mode ......................................................................................................... 156
4.3.1.1 Through GridBuilder ................................................................................. 156
4.3.1.1.1 Pager customization ............................................................... 158
4.3.1.2 Through GridPropertiesModel................................................................... 160
4.3.1.2.1 Pager customization ............................................................... 162
4.3.2 JSON Mode .......................................................................................................... 163
4.3.2.1 Through GridBuilder ................................................................................. 163
4.3.2.1.1 Pager Customization............................................................... 165
4.3.2.2 Through GridPropertiesModel................................................................... 167
4.3.2.2.1 Pager Customization............................................................... 168
4.3.3 Pager Customization............................................................................................. 169
4.3.3.1 Customizing the Grid Pager in an Application ........................................... 170
4.3.3.1.1 Through GridBuilder ................................................................ 170
4.3.3.1.2 Through GridPropertiesModel ................................................. 172
4.4 Sorting .............................................................................................................................. 176
4.4.1 Server Mode ......................................................................................................... 177
4.4.1.1 Through GridBuilder ................................................................................. 177
4.4.1.1.1 Sorting customization .............................................................. 181
4.4.1.2 Through GridPropertiesModel................................................................... 183
4.4.1.2.1 Sorting Customization ............................................................. 185
4.4.2 JSON Mode .......................................................................................................... 187
4.4.2.1 Through GridBuilder ................................................................................. 187
4.4.2.1.1 Sorting Customization ............................................................. 190
4.4.2.2 Through GridPropertiesModel................................................................... 192
4.4.2.2.1 Sorting Customization ............................................................. 195
4.5 Filtering ............................................................................................................................. 197
4.5.1 Server Mode ......................................................................................................... 202

© 2014 Syncfusion. All rights reserved. 4 | Page


Essential Grid for ASP.NET MVC Classic

4.5.1.1 Through GridBuilder ................................................................................. 202


4.5.1.1.1 Filter Customization ................................................................ 205
4.5.1.2 Through GridPropertiesModel................................................................... 209
4.5.1.2.1 Filter Customization ................................................................ 211
4.5.2 JSON Mode .......................................................................................................... 213
4.5.2.1 Through GridBuilder ................................................................................. 213
4.5.2.1.1 Filter Customization ................................................................ 215
4.5.2.2 Through GridPropertiesModel................................................................... 218
4.5.2.2.1 Filter Customization ................................................................ 220
4.5.3 Filter Bar ............................................................................................................... 221
4.5.3.1 Properties ................................................................................................ 222
4.5.3.2 Filter Tokens ............................................................................................ 223
4.5.3.3 Adding the Filter Bar to an MVC Grid ........................................................ 224
4.5.3.3.1 Through GridBuilder ................................................................ 224
4.5.3.3.2 Through GridProperties model ................................................ 227
4.5.3.4 How to Filter Data Using Filter Tokens in the Filter Bar ............................. 230
4.5.4 Searching ............................................................................................................. 230
4.5.4.1 Through GridBuilder ................................................................................. 230
4.5.4.2 Through GridPropertiesModel................................................................... 234
4.6 Grouping ........................................................................................................................... 237
4.6.1 Server Mode ......................................................................................................... 237
4.6.1.1 Through GridBuilder ................................................................................. 238
4.6.1.1.1 Grouping Customization .......................................................... 242
4.6.1.2 Through GridPropertiesModel................................................................... 243
4.6.1.2.1 Grouping Customization .......................................................... 246
4.6.2 JSON Mode .......................................................................................................... 247
4.6.2.1 Through GridBuilder ................................................................................. 247
4.6.2.1.1 Grouping Customization .......................................................... 250
4.6.2.2 Through GridPropertiesModel................................................................... 251
4.6.2.2.1 Grouping Customization .......................................................... 254
4.7 Editing............................................................................................................................... 254
4.7.1 Server Mode ......................................................................................................... 259
4.7.1.1 Through GridBuilder ................................................................................. 259
4.7.1.1.1 Grid EditMode Configuration ................................................... 269
4.7.1.1.2 Disable Editing in Specified Columns ...................................... 280

© 2014 Syncfusion. All rights reserved. 5 | Page


Essential Grid for ASP.NET MVC Classic

4.7.1.2 Through GridPropertiesModel................................................................... 282


4.7.1.2.1 Grid EditMode Configuration ................................................... 290
4.7.2 JSON Mode .......................................................................................................... 301
4.7.2.1 Through GridBuilder ................................................................................. 301
4.7.2.1.1 Grid EditMode Configuration ................................................... 310
4.7.2.2 Through GridPropertiesModel................................................................... 320
4.7.2.2.1 Grid EditMode Configuration ................................................... 328
4.7.3 Adding Editing-Rows............................................................................................. 339
4.7.3.1 Properties ................................................................................................ 339
4.7.3.2 Configuring an editing-row ........................................................................ 340
4.7.3.2.1 Through GridBuilder ................................................................ 340
4.7.3.2.2 Through GridPropertiesModel ................................................. 345
4.7.4 CellEditType ......................................................................................................... 351
4.7.4.1 Configuring CellEditType .......................................................................... 351
4.7.4.1.1 Through GridBuilder ................................................................ 352
4.7.4.1.2 Through GridPropertiesModel ................................................. 358
4.7.4.2 Tables for Properties, Methods, and Events.............................................. 364
4.7.5 Excel-Like Editing in MVC Grid ............................................................................. 366
4.7.5.1 Enabling Excel-Like Editing in MVC Grid .................................................. 369
4.7.5.1.1 Through GridBuilder ................................................................ 369
4.7.5.1.2 Through GridPropertiesModel ................................................. 375
4.7.6 Dialog editing in MVC Grid .................................................................................... 380
4.7.6.1 Properties and Events Tables ................................................................... 381
4.7.6.2 Enabling Dialog Editing in MVC Grid......................................................... 384
4.7.6.2.1 Through GridBuilder ................................................................ 384
4.7.6.2.2 Through GridPropertiesModel ................................................. 391
4.7.6.3 Edit Mode Configuration ........................................................................... 397
4.7.7 External Form Edit Mode ...................................................................................... 407
4.7.7.1 Properties ................................................................................................ 409
4.7.7.2 Enabling External Form Edit Mode in Grid MVC........................................ 410
4.7.7.2.1 Through GridBuilder ................................................................ 410
4.7.7.2.2 Through GridProperties model ................................................ 415
4.7.8 Unbound Column Editing ...................................................................................... 421
4.7.8.1 Properties Tables ..................................................................................... 422
4.7.8.2 Appearance.............................................................................................. 424

© 2014 Syncfusion. All rights reserved. 6 | Page


Essential Grid for ASP.NET MVC Classic

4.7.8.3 Enabling Unbound Column Editing in MVC Grid ....................................... 425


4.7.8.3.1 Server Mode ........................................................................... 425
4.7.8.3.2 JSON Mode ............................................................................ 442
4.7.9 Editable and Repository class details .................................................................... 459
4.7.9.1 EditableOrder Class ................................................................................. 459
4.7.9.2 OrderRepository Class ............................................................................. 461
4.7.9.3 JSONOrder Class..................................................................................... 463
4.7.9.4 AutoFormatting Class ............................................................................... 464
4.7.9.5 AutoFormatting Repository ....................................................................... 465
4.7.9.6 OrderDetailEdit Class ............................................................................... 466
4.7.9.7 OrderDetailRepository .............................................................................. 466
4.8 Exporting........................................................................................................................... 468
4.8.1 Excel Export ......................................................................................................... 468
4.8.1.1 Through GridBuilder ................................................................................. 469
4.8.1.2 Through GridPropertiesModel................................................................... 472
4.8.1.3 Exporting through Custom Buttons ........................................................... 476
4.8.2 PDF Export ........................................................................................................... 480
4.8.2.1 Appearance and Structure of PDF Export ................................................. 480
4.8.2.2 Adding PDF Export Support to MVC Grid ................................................. 483
4.8.2.2.1 Through GridBuilder ................................................................ 483
4.8.2.2.2 Through GridPropertiesModel ................................................. 484
4.8.3 Word Export.......................................................................................................... 486
4.8.3.1 Appearance and Structure of the Word Export .......................................... 486
4.8.3.2 Adding Word Export to MVC Grid ............................................................. 489
4.8.3.2.1 Through GridBuilder ................................................................ 489
4.8.3.2.2 Through GridPropertiesModel ................................................. 490
4.8.4 Properties ............................................................................................................. 492
4.8.5 Methods ............................................................................................................... 494
4.8.6 Events .................................................................................................................. 495
4.8.7 How to Format Cells and Rows in a Grid that Was Exported to PDF...................... 495
4.8.7.1.1 For PDF .................................................................................. 495
4.8.7.1.2 For Word ................................................................................ 500
4.9 Formatting......................................................................................................................... 505
4.9.1 Column Formatting ............................................................................................... 506
4.9.1.1 Using Format() ......................................................................................... 506

© 2014 Syncfusion. All rights reserved. 7 | Page


Essential Grid for ASP.NET MVC Classic

4.9.1.2 Using CssClass()...................................................................................... 509


4.9.2 Custom Formatting ............................................................................................... 512
4.9.2.1 QueryCellInfo Action ................................................................................ 512
4.9.2.1.1 Server Mode ........................................................................... 514
4.9.2.1.2 JSON Mode ............................................................................ 521
4.9.2.2 RowDataBound Action ............................................................................. 526
4.9.2.2.1 Server Mode ........................................................................... 527
4.9.2.2.2 JSON Mode ............................................................................ 532
4.9.3 Conditional Formating ........................................................................................... 537
4.9.3.1 Through GridBuilder ................................................................................. 538
4.9.3.2 Through GridPropertiesModel................................................................... 542
4.10 Summaries ........................................................................................................................ 545
4.10.1 Server Mode ......................................................................................................... 551
4.10.1.1 Through GridBuilder..................................................................... 551
4.10.1.2 Through GridPropertiesModel ...................................................... 554
4.10.2 JSON Mode .......................................................................................................... 558
4.10.2.1 Through GridBuilder..................................................................... 558
4.10.2.2 Through GridPropertiesModel ...................................................... 561
4.11 Scrolling ............................................................................................................................ 564
4.11.1 Scrolling ............................................................................................................... 564
4.11.1.1 Through GridBuilder..................................................................... 565
4.11.1.2 Through GridPropertiesModel ...................................................... 569
4.11.2 Virtual Scrolling in MVC Grid ................................................................................. 572
4.11.2.1 Virtual Scrolling Mode .................................................................. 573
4.11.2.1.1 Normal Mode ........................................................................ 573
4.11.2.1.2 Facebook Mode .................................................................... 579
4.12 Selection ........................................................................................................................... 583
4.12.1 Toggle Selection ................................................................................................... 587
4.12.1.1 Through GridBuilder..................................................................... 587
4.12.1.2 Through GridPropertiesModel ...................................................... 590
4.13 Drag and Drop................................................................................................................... 592
4.13.1 Dragging and Dropping Grid Rows into Any Other Element ................................... 592
4.13.1.1 Through GridBuilder..................................................................... 595
4.13.1.2 Through GridPropertiesModel ...................................................... 597
4.13.2 Drag Any Other Element and Drop into Grid ......................................................... 599

© 2014 Syncfusion. All rights reserved. 8 | Page


Essential Grid for ASP.NET MVC Classic

4.13.2.1 Through GridBuilder..................................................................... 602


4.13.2.2 Through GridPropertiesModel ...................................................... 603
4.13.2.3 Properties Explanation ................................................................. 606
4.14 Keyboard Interface ............................................................................................................ 608
4.14.1 Adding Keyboard Interface Support to an Application ............................................ 610
4.14.1.1 Enabling Keyboard Interface with Default Keys ............................ 610
4.14.1.1.1 Through GridBuilder .............................................................. 610
4.14.1.1.2 Through GridPropertiesModel ............................................... 611
4.14.1.2 Configuring the Default Keys........................................................ 613
4.14.1.2.1 Through GridBuilder .............................................................. 613
4.14.1.2.2 Through GridPropertiesModel ............................................... 615
4.14.2 Tables for Properties, Methods, and Events .......................................................... 616
4.15 Context Menu .................................................................................................................... 621
4.15.1 Built-in Context Menu Items .................................................................................. 621
4.15.1.1 Through GridBuilder..................................................................... 626
4.15.1.2 Through GridPropertiesModel ...................................................... 630
4.15.2 Property, Method, and Event Tables ..................................................................... 634
4.15.2.1 Property Tables ........................................................................... 634
4.15.2.2 Methods ...................................................................................... 636
4.15.2.3 Client-Side Events ....................................................................... 637
4.15.3 Customizing the Context Menu ............................................................................. 637
4.15.3.1 Through GridBuilder..................................................................... 637
4.15.3.2 Through GridPropertiesModel ...................................................... 643
4.16 Appearance....................................................................................................................... 647
4.16.1 Built-in Skin Styles ................................................................................................ 647
4.16.1.1 Through GridBuilder..................................................................... 648
4.16.1.2 Through GridPropertiesModel ...................................................... 650
4.16.2 Customizing the Grid Appearance ......................................................................... 652
4.16.2.1 Through GridBuilder..................................................................... 653
4.16.2.2 Through GridPropertiesModel ...................................................... 660
4.17 Localization ....................................................................................................................... 667
4.17.1 Adding Localization to an Application .................................................................... 668
4.17.1.1 Through GridBuilder..................................................................... 668
4.17.1.1.1 Customization ....................................................................... 672
4.17.1.2 Through GridPropertiesModel ...................................................... 673

© 2014 Syncfusion. All rights reserved. 9 | Page


Essential Grid for ASP.NET MVC Classic

4.17.1.2.1 Customization ....................................................................... 676


4.18 Hierarchical Grid ............................................................................................................... 678
4.18.1 Server Mode ......................................................................................................... 678
4.18.1.1 Through GridBuilder..................................................................... 678
4.18.2 JSON Mode .......................................................................................................... 681
4.18.2.1 Through GridBuilder..................................................................... 681
4.18.3 Editing 688
4.18.3.1 Server Mode ................................................................................ 688
4.18.3.1.1 Through GridBuilder .............................................................. 688
4.18.3.2 JSON Mode ................................................................................. 697
4.18.3.2.1 Through GridBuilder .............................................................. 697
4.19 Stacked Headers ............................................................................................................... 706
4.19.1 Enabling Stacked Headers in Grid MVC ................................................................ 710
4.19.1.1 Through GridBuilder..................................................................... 710
4.19.1.2 Through GridPropertiesModel ...................................................... 713
4.20 Merge Cells ....................................................................................................................... 716
4.20.1 Tables for Properties, Methods, and Events .......................................................... 716
4.20.2 Adding Merge Cells to an Application .................................................................... 718
4.20.2.1 Server Mode ................................................................................ 718
4.20.2.1.1 Through GridBuilder .............................................................. 718
4.20.2.1.2 Through GridPropertiesModel ............................................... 723
4.20.2.2 JSON Mode ................................................................................. 725
4.20.2.2.1 Through GridBuilder .............................................................. 726
4.20.2.2.2 Through GridPropertiesModel ............................................... 730
4.21 Freezing Rows and Columns............................................................................................. 732
4.21.1.1 Freezing Grid Rows/Columns in an Application ............................ 733
4.21.1.1.1 Through GridBuilder .............................................................. 733
4.21.1.1.2 Through GridPropertiesModel ............................................... 736
4.21.1.2 Freezing Panes ........................................................................... 740
4.21.1.3 Unfreezing Panes ........................................................................ 741
4.21.1.4 Appearance ................................................................................. 743
4.22 Auto Wrap-Up of Column Cells .......................................................................................... 743
4.22.1 Properties ............................................................................................................. 744
4.22.2 Enabling Auto Wrap-Up in Grid MVC .................................................................... 747
4.22.2.1 Through GridBuilder..................................................................... 747

© 2014 Syncfusion. All rights reserved. 10 | Page


Essential Grid for ASP.NET MVC Classic

4.22.2.2 Through GridPropertiesModel ...................................................... 749


4.23 Client-Side Events and Methods........................................................................................ 751
4.23.1 Adding Handlers ................................................................................................... 774
4.23.1.1 Through GridBuilder..................................................................... 774
4.23.1.2 Through GridPropertiesModel ...................................................... 779
4.23.1.3 Through Grid Client Object........................................................... 780
4.23.2 Arguments details for the ClientSide events. ......................................................... 781
4.23.3 Removing Handlers from Grid ............................................................................... 783
4.23.4 Expand/Collapse Grouped column ........................................................................ 784
4.23.5 Set Methods ......................................................................................................... 786
4.23.5.1 Primary key collection .................................................................. 786
4.23.5.2 Current Page ............................................................................... 787
4.23.5.3 Page Size .................................................................................... 788
4.23.5.4 Direction for the Enter key ............................................................ 789
4.23.5.5 Direction for the Tab key .............................................................. 790
4.23.6 Select and Deselect Methods............................................................................... 791
4.23.6.1 Row ............................................................................................. 791
4.23.6.2 Current Cell ................................................................................. 793
4.23.6.3 Multiple rows in a Grid ................................................................. 794
4.23.6.4 Entire Grid ................................................................................... 795
4.23.7 Show and Hide Methods ....................................................................................... 796
4.23.7.1 Row ............................................................................................. 796
4.23.7.2 Column ........................................................................................ 798
4.23.7.2.1 By ColumnName ................................................................... 798
4.23.7.2.2 By ColumnIndex.................................................................... 799
4.23.7.3 GroupDropArea ........................................................................... 801
4.23.7.4 RowHeader ................................................................................. 803
4.23.8 Enable/Disable Methods ....................................................................................... 804
4.23.8.1 RowHover.................................................................................... 804
4.23.8.2 Editing functionality ...................................................................... 806
4.23.8.3 Grouping functionality .................................................................. 808
4.23.8.4 Paging functionality ...................................................................... 810
4.23.8.5 Selection functionality .................................................................. 812
4.23.9 sampleCustomize Methods ................................................................................... 814
4.23.9.1 Current Cell ................................................................................. 814

© 2014 Syncfusion. All rights reserved. 11 | Page


Essential Grid for ASP.NET MVC Classic

4.23.9.2 Current Selected Area ................................................................. 815


4.23.9.3 Current Selected Row Header...................................................... 816
4.23.9.4 Current Selected Column Header ................................................ 817
4.23.9.5 Clone element of a dragged column ............................................. 818
4.23.10 Sorting Methods.................................................................................................... 819
4.23.10.1 Sorting ......................................................................................... 819
4.23.10.2 Clear Sorting................................................................................ 820
4.23.11 Grouping Methods ................................................................................................ 821
4.23.11.1 Group Column ............................................................................. 821
4.23.11.2 Ungroup Column.......................................................................... 822
4.23.12 Reorder Method .................................................................................................... 823
4.23.12.1 ReOrder Columns ........................................................................ 823
4.23.13 How to send the request to the Grid using External Button .................................... 824
4.23.13.1 Searching Request ...................................................................... 824
4.23.13.2 Paging Request ........................................................................... 825
4.23.13.3 Filtering Request.......................................................................... 825
4.23.13.4 Sorting Request ........................................................................... 826
4.23.13.5 Grouping Request........................................................................ 826
4.23.13.6 Excel Export Request .................................................................. 827
4.23.13.7 Word Export Request................................................................... 827
4.23.13.8 PDF Export Request .................................................................... 827
4.23.13.9 AddNew Request ......................................................................... 828
4.23.13.10 Editing Request ........................................................................... 828
4.23.13.11 Save Request .............................................................................. 829
4.23.13.12 Delete Request ............................................................................ 829
4.23.13.13 Cancel Request ........................................................................... 829
4.23.13.14 Refresh Request .......................................................................... 830
4.23.13.15 HTML Action Request .................................................................. 830
4.24 Passing Values between Grid Actions ............................................................................... 831
4.24.1 Through GridBuilder.............................................................................................. 831
4.24.2 Through GridPropertiesModel ............................................................................... 832
4.25 Column Templates ............................................................................................................ 833
4.25.1 Adding Template to the Grid Column in an Application .......................................... 833
4.25.1.1 Server Mode ................................................................................ 835
4.25.1.2 JSON Mode ................................................................................. 837

© 2014 Syncfusion. All rights reserved. 12 | Page


Essential Grid for ASP.NET MVC Classic

4.26 Toolbar.............................................................................................................................. 840


4.26.1 Adding the Grid Toolbar in an Application.............................................................. 841
4.26.2 Customizing the Grid Toolbar in an Application ..................................................... 841
4.26.2.1 Through GridBuilder..................................................................... 841
4.26.2.2 Through GridPropertiesModel ...................................................... 844
4.26.3 GridPropertiesModel Table ................................................................................... 846
4.26.3.1 ToolbarOptions Table .................................................................. 846
4.26.4 Methods ............................................................................................................... 847
4.26.5 Events 849
4.27 MultiColumnDropDown...................................................................................................... 849
4.27.1 Elaborate Structure of MultiColumnDropDown ...................................................... 850
4.27.2 Adding Essential MultiColumnDropDown to an Application .................................... 851
4.27.3 Concepts and Features ......................................................................................... 853
4.27.3.1 Data Binding ................................................................................ 853
4.27.3.1.1 Through Builder .................................................................... 854
4.27.3.1.2 Through MultiColumnDropDownModel .................................. 855
4.27.3.2 Appearance ................................................................................. 857
4.27.3.2.1 Through Builder .................................................................... 860
4.27.3.2.2 Through MultiDropdownModel............................................... 861
4.27.3.3 RightToLeft .................................................................................. 863
4.27.3.3.1 Through Builder .................................................................... 864
4.27.3.3.2 Through MultiColumnDropDownModel .................................. 866
4.27.3.4 Setting the Orientation ................................................................. 872
4.27.3.4.1 Through Builder .................................................................... 873
4.27.3.4.2 Through MultiDropDownModel .............................................. 875
4.27.3.5 Defining the Display Conditions.................................................... 877
4.27.3.5.1 Through Builder .................................................................... 877
4.27.3.5.2 Through MultiDropdownModel............................................... 879
4.27.3.6 Column Mapping.......................................................................... 881
4.27.3.6.1 Through Builder .................................................................... 882
4.27.3.6.2 Through MultiColumnDropDownModel .................................. 884
4.27.3.7 Client-Side Events ....................................................................... 887
4.27.3.7.1 Adding Handlers through Builder ........................................... 891
4.27.3.7.2 Adding Handlers through
MultiColumnDropDownModel ....................................................... 893

© 2014 Syncfusion. All rights reserved. 13 | Page


Essential Grid for ASP.NET MVC Classic

4.27.3.8 Client-Side Methods..................................................................... 894


4.27.3.9 Sorting ......................................................................................... 896
4.27.3.9.1 Server Mode ......................................................................... 896
4.27.3.9.2 JSON Mode .......................................................................... 902
4.27.3.10 Filtering in the MultiColumnDropDown Control ............................. 913
4.27.3.10.1 Server Mode ....................................................................... 916
4.27.3.10.2 JSON Mode ........................................................................ 921
4.28 Code samples ................................................................................................................... 923

5 How to 927
5.1 Adding a Model to the Application...................................................................................... 927
5.2 Settings for Essential Grid in MVC 4 Application ................................................................ 930
5.3 Strongly Typed View ......................................................................................................... 932
5.3.1 Creating a Strongly Typed View ............................................................................ 932
5.3.2 Creating a Strongly Typed View Manually ............................................................. 934
5.4 Create the ADO.NET Entity Data Model ............................................................................ 935
5.5 Create the Generic Collection Model ................................................................................. 940
5.6 Create the Grid using view customization with Default view ............................................... 943
5.7 How to manually configure the MVC application for Grid .................................................... 945
5.7.1 Creating a Platform Application ............................................................................. 945
5.7.2 Adding Essential Grid to the Application Using ASPX ............................................ 950
5.7.2.1 Adding Reference Assemblies .................................................................. 950
5.7.2.2 Adding Scripts .......................................................................................... 953
5.7.2.3 Adding Codes to the Web.config File ........................................................ 956
5.7.2.4 Add StyleManager and ScriptManager ..................................................... 958
5.7.2.4.1 Adding StyleManager .............................................................. 958
5.7.2.4.2 Adding ScriptManager............................................................. 959
5.7.2.5 Creating the Grid control .......................................................................... 959
5.7.2.5.1 Through GridBuilder ................................................................ 959
5.7.2.5.2 Through GridPropertiesModel ................................................. 961
5.7.3 Adding Essential Grid to the Application Using Razor ........................................... 965
5.7.3.1 Adding Reference Assemblies .................................................................. 966
5.7.3.2 Adding Scripts .......................................................................................... 968
5.7.3.3 Adding Codes to the Web.config File ........................................................ 971
5.7.3.4 Adding Codes to the Views Web.config file (Views\Web.config) ................ 974

© 2014 Syncfusion. All rights reserved. 14 | Page


Essential Grid for ASP.NET MVC Classic

5.7.3.5 Add StyleManager and ScriptManager ..................................................... 974


5.7.3.5.1 Adding StyleManager .............................................................. 974
5.7.3.5.2 Adding ScriptManager............................................................. 975
5.7.3.6 Creating the Grid Control .......................................................................... 975
5.7.3.6.1 Through GridBuilder ................................................................ 975
5.7.3.6.2 Through GridPropertiesModel ................................................. 977
5.7.4 Adding Essential Grid to the Simple Razor Application using VB ........................... 981
5.7.4.1 Adding Reference Assemblies .................................................................. 982
5.7.4.2 Adding Scripts .......................................................................................... 983
5.7.4.3 Adding Codes to the Web.config file ......................................................... 986
5.7.4.4 Adding Codes to the Views Web.config file (Views\Web.config) ................ 988
5.7.4.5 Add StyleManager and ScriptManager ..................................................... 989
5.7.4.5.1 Adding StyleManager .............................................................. 989
5.7.4.5.2 Adding ScriptManager............................................................. 989
5.7.4.6 Creating the Grid Control in the View ........................................................ 990
5.7.5 Elaborate Structure of the Control ......................................................................... 992
5.7.5.1 Elements and Features ............................................................................ 993
5.7.6 Feature Summary ................................................................................................. 993
5.7.6.1 Appearance.............................................................................................. 994
5.7.6.2 Grouping .................................................................................................. 994
5.7.6.3 Sorting 995
5.7.6.4 Filtering 996
5.7.6.5 Paging 996
5.7.6.6 Editing 997
5.7.6.7 Exporting................................................................................................ 1000
5.7.6.8 Summaries ............................................................................................. 1001
5.7.6.9 Scrolling ................................................................................................. 1002
5.7.6.10 Formatting Data ......................................................................... 1002
5.7.6.11 Unbound Column Support.......................................................... 1006
5.7.6.12 Drag-and-Drop Support.............................................................. 1006
5.7.6.13 Client-Side Interactivity .............................................................. 1006
5.8 How do I Add Essential Grid to the Simple MVC 4 Razor Application? ............................. 1009
5.8.1 Adding reference assemblies .............................................................................. 1009
5.8.2 Adding Scripts .................................................................................................... 1011
5.8.3 Configure the root Web.config file ....................................................................... 1014

© 2014 Syncfusion. All rights reserved. 15 | Page


Essential Grid for ASP.NET MVC Classic

5.8.4 Configuring the Views Web.config (Views\Web.config) ........................................ 1016


5.8.5 Adding StyleManager.......................................................................................... 1016
5.8.6 Adding ScriptManager ........................................................................................ 1017
5.8.7 Creating the Grid Control in the View .................................................................. 1017
5.9 How to avoid Grid Invisibility ............................................................................................ 1019
5.10 How to Use Other Controls Inside the DialogEditorTemplate?.......................................... 1023
5.11 How to create and assign columns to a grid in the controller through the grid-
properties model ............................................................................................................. 1023
5.12 How to: overcome “Registering style sheet for the Grid failed because assembly
does not exist” error ........................................................................................................ 1026
5.13 How to: Resolve Database configuration error ................................................................ 1027
5.14 How to: Avoid validation messages invisibility .................................................................. 1028
5.15 How to: Refresh grid contents on external button click .................................................... 1028
5.16 How to: Get the selected row values in ToolbarClick event .............................................. 1029
5.17 How to: Set Grid height and width in Client-Side .............................................................. 1031
5.18 How to: overcome “Check whether the grid post action is defined in controller”
error when editing............................................................................................................ 1032
5.19 How to: Format the Grid columns .................................................................................... 1035
5.20 Hiding Row Header in Grid .............................................................................................. 1035
5.21 How to: Hide columns when exporting Grid...................................................................... 1036
5.22 How to: Disable sorting for specific columns in Grid ......................................................... 1038
5.23 How to: Get properties of the grid ................................................................................... 1039
5.24 How to: Get selected records in another view .................................................................. 1039
5.25 How to: Show tooltip on Grid Cell MouseHover in Server mode ....................................... 1042
5.26 How to: Show tooltip on Grid Cell MouseHover in JSON mode ........................................ 1043
5.27 How to: Format the cells through QueryCellInfo event ..................................................... 1045
5.28 How to: Get custom theme for multiple (Grid, Tools, Schedule) controlsHow to:
Move Grid rows Up and Down using Button ..................................................................... 1047
5.29 How to: Hide filter icon in grid table header ...................................................................... 1049
5.30 How to: Set the height of the grid rows ............................................................................ 1050
5.31 How to: Use one column data value in another column .................................................... 1050
5.32 How to: Custom server paging with initial grouping .......................................................... 1051
5.33 How to: Use alternate row color background .................................................................... 1053
5.34 How to: Right align summary row values ......................................................................... 1053
5.35 How to: Format the values in the filter dialog.................................................................... 1054
5.36 How to: Add New, Delete and Update multiple grids uing external button ......................... 1055

© 2014 Syncfusion. All rights reserved. 16 | Page


Essential Grid for ASP.NET MVC Classic

5.37 How to: Save the Grid Content using an External Button. ................................................ 1060
5.38 How to: Change dropdown to textbox cell for particular cells when celledit type is
dropdown ........................................................................................................................ 1060
5.39 How to: Hide MasterCellCollapse/Expand in Hierarchy Grid ............................................. 1062
5.40 How to: Hide GroupHeaderArea when Grouping is defined in code.................................. 1063
5.41 How to: Assign datasource for a DropdownEdit at clientside ............................................ 1064
5.42 How to: Update the cell value at client side ...................................................................... 1067
5.43 How to: Change entire column values in client side.......................................................... 1068
5.44 How to: Check which column is filtered in the OnActionSuccess Client-Side
event. .............................................................................................................................. 1074
5.45 How to: Use waiting popup of grid, in Client-Side event of the grid in toolbar
button?............................................................................................................................ 1075
5.46 How to: Add a hyperlink to unbound Column of MVC Grid ............................................... 1077
5.47 How to: Remove up and down arrows in numeric textbox ................................................ 1078
5.48 How to: Set grouping initially with datatable elements ...................................................... 1080
5.49 How to: Apply manual filtering to the grid with Queryparam.............................................. 1081
5.50 How to: Avoid the duplicate row insertion and display error message ............................... 1083
5.51 How to: Import an Excel(.xlsx) file into Grid ...................................................................... 1085
5.52 How to: Load only required rows from database, instead of loading all data. .................... 1087
5.53 How to: Enum Dropdown in grid ...................................................................................... 1087
5.54 How to: Store the Grouping, Sorting, Filtering and Columns Info in XML .......................... 1088
5.55 How to: Multiple Grid not showing on JQuery tabs ........................................................... 1091
5.56 How to: Preventing Grid focus at the top of grid ............................................................... 1093
5.57 How to: Programmatically filter a column ......................................................................... 1094
5.58 How to: Set the number of records per page and for subsequent pages, by
default. ............................................................................................................................ 1101
5.59 How to: Set Image Column using Url.Content .................................................................. 1102
5.60 How to: Bind Javascript onkeypress event on editcell ...................................................... 1103
5.61 How to: Click automation of the edit dialog save button.................................................... 1104
5.62 How to: Use AntiForgeryToken with Grid Editing.............................................................. 1106

© 2014 Syncfusion. All rights reserved. 17 | Page


Essential Grid for ASP.NET MVC Classic

1 Overview
1.1 Introduction to Essential Grid for ASP.NET MVC

Essential Grid for ASP.NET MVC is a feature-rich control that provides extensive appearance
customization options with support for grouped records. With Essential Grid for ASP.NET MVC,
you can create a grid with a highly customizable look and feel. This grid is very useful for
generating complex grid-based reports with rich formatting. It supports paging, sorting, grouping,
filtering, and editing features. It also supports a JSON mode in which you can handle all the
operations like paging and sorting. The performance of these operations in the JSON mode will
be much faster than if the grid were to handle them. Essential Grid generates clean HTML in
compliance with XHTML 1.0. It supports any kind of IEnumerable data source. It uses LINQ data
retrieval techniques for handling data sources, and offers high performance.

Real World Scenarios


Grid editing—Essential Grid provides rich server APIs for inserting new data, updating the
existing data, and deleting data from the specified data source.

Figure 1: Essential Grid for ASP.NET MVC

© 2014 Syncfusion. All rights reserved. 18 | Page


Essential Grid for ASP.NET MVC Classic

Developers can make use of Essential Grid to generate complex grid-based reports with rich
formatting.

At its core, the grid functions as a very efficient display engine for tabular data that can be
customized down to the cell level. It does not make any assumptions on the structure of the data
(many grid controls implemented as straight data-bound controls make such explicit
assumptions). This leads to a very flexible design that can be easily adapted to a variety of tasks
including the display of completely unstructured data and the display of structured data from a
database.

The display system also hosts a powerful and complete styles architecture. Settings can be
specified at the cell level or at higher levels using parent styles that are referred to as base styles.
Base styles can affect groups of cells. Cell level settings override any higher level settings and
enable easy customization right down to that level.

Key Features
Some important features of Grid for MVC are listed below.
 Highly customizable look and feel—Fill the Grid control with data from any data source
and render it as an image in a browser.
 Data sources—Bind the Grid control with any data source. For example, all IEnumerable
data sources.
 Navigation—Offers complete navigational support for navigating between the grid cells,
rows, and pages.
 Sorting and grouping—Supports n levels of sorting and grouping.
 Filtering—Offers Excel-like filtering for filter data.
 Editing—Offers three editing modes for inserting, editing, and deleting records in a grid.
 Conditional formatting—Provides an option to format grid cells based on a certain
condition.
 Drag-and-drop records—Exposes flexible client-side events to drag-and-drop grid
records over other HTML elements on the page.
 Summary support—Offers options for specifying summary rows and columns.
 Column formatting—Columns can be formatted directly from view.
 JSON mode—Offers support for JSON mode. You can handle operations and send the
data in JSON mode to view data which is displayed in ASP.NET 4.0 templates.
 Unbound columns—Offers option for specifying unbound columns.
 Drag-and-drop support—Allows you to drag any column and drop it at any position in the
grid, allowing columns to be repositioned at the required place.
 Resize rows and columns—Grid provides option for resizing the rows and columns.
 Hide rows and columns—The grid provides support to hide or unhide a range of rows and
columns.
 Selection modes—Essential Grid offers different kinds of selections such as row only,
column only, cell only for the selection of a particular row, or an entire grid selection.
 Complete AJAX support—Enables faster output.
 Complete XHTML compliance—Provides the best results on all browsers.

© 2014 Syncfusion. All rights reserved. 19 | Page


Essential Grid for ASP.NET MVC Classic

1.2 Prerequisites and Compatibility


This section covers the requirements mandatory for using the Grid control. It also lists operating
systems and browsers compatible with the product.

Prerequisites
The prerequisites details are listed below:
Table 1: Prerequisites Table

 Visual Studio 2013


 Visual Studio 2012
 Visual Web Developer® 2012 Express Edition
Development Environments  Visual Studio 2010
 Visual Web Developer® 2010 Express Edition
 Visual Web Developer® 2008 Express Edition
 Visual Studio 2008
 .NET 4.5
.NET Framework Versions  .NET 4.0
 .NET 3.5
 ASP.NET MVC 4.0
ASP.NET MVC Framework
 ASP.NET MVC 3.0
Versions
 ASP.NET MVC 2.0

Compatibility
The compatibility details are listed below:
Table 2: Compatibility Table

 Windows 8.1 (32 bit and 64 bit)


 Windows Server 2008 (32 bit and 64 bit)
 Windows Server 2003 (32 bit and 64 bit)
Operating Systems
 Windows 7 (32 bit and 64 bit)
 Windows Vista (32 bit and 64 bit)
 Windows XP
 IIS 6.0+
Web Servers
 Visual Studio built-in Web server for development
 Internet Explorer 7+
 Mozilla 2.0+
Browser Support  Safari 3.0+
 Opera 9+
 Chrome 1+

© 2014 Syncfusion. All rights reserved. 20 | Page


Essential Grid for ASP.NET MVC Classic

1.3 Documentation
Syncfusion provides the following documentation segments to provide all the necessary
information pertaining to the Grid control.

Type of documentation Location

C:\Program Files (x86)\Syncfusion\Essential


Studio\11.1.0.21\Infrastructure\Read Me
Readme
[drive:]\Program Files(x86)\Syncfusion\Essential Studio\<Version
Number>\Infrastructure\Read Me \ASPMVC.html

[drive:]\Program Files(x86)\Syncfusion\Essential Studio\<Version


Release Notes
Number>\Infrastructure\ Release Notes\ASPMVC.html

User Guide (this document) Online


http://help.syncfusion.com/resources(Navigate to the Grid for
ASP.NET MVC User Guide.)

Note: Click Download as PDF to access a PDF version.

Class Reference Online


http://help.syncfusion.com/resources (Navigate to the ASP.NET
MVC User Guide. Select Grid in the second text box, and then click
the Class Reference link found in the upper right section of the
page.)

© 2014 Syncfusion. All rights reserved. 21 | Page


Essential Grid for ASP.NET MVC Classic

2 Installation and Deployment


2.1 Deployment Requirements
This section provides information and instructions for deploying ASP.NET MVC applications that
use Essential Grid for MVC.

Marking the Application Directory

The appropriate directory usually where the project file is saved must be marked as an
Application in IIS.

Referencing Syncfusion Assemblies

The Syncfusion assemblies can be deployed in either the server's GAC (Global Assembly Cache)
or the application's Bin folder.

General Instructions
Data Files

If you have XML, .mdb, or other data files, ensure that they have sufficient security permissions.
The Authenticated Users should have access to the files and the directory to give the ASP.NET
code enough permission to open the file at run time.

Supporting Netscape/Firefox/Mozilla

Ensure that the Machine.config's (of the deployed system) <browserCaps> section includes
appropriate entries for Mozilla, and so on. The default entries consider these browsers as
downlevel and hence will not render Syncfusion and your controls properly.

Deploying in Medium Trust or Partial Trust Scenarios

There are 2 such scenarios in which Syncfusion assemblies might be deployed.

1. Syncfusion assemblies in the GAC (Global Assembly Cache) and application running in
medium trust.
1.
This means the Syncfusion assemblies are running in full trust which is explained in Default
Deployment Pattern. This scenario is fully supported and there are no additional steps
necessary.

2. Syncfusion assemblies in the application Bin folder and application running in medium
trust.

© 2014 Syncfusion. All rights reserved. 23 | Page


Essential Grid for ASP.NET MVC Classic

This means both the Syncfusion assemblies and the application code are running in partial
trust which is explained in Fast Deployment Pattern. In this case, the control’s
DeprecateFunctionalityToRunInPartialTrust property should be turned on for the control
to work properly. This also means some features might not be available. See the control's
documentation for more info.

2.1.1 Default Deployment Pattern


Follow the steps below to deploy the application in the development server by referencing the
dynamic-link library in GAC.
1. The Web.config file should be configured according to the referenced DLLs. For more
information on the Web.config file configuration please refer to the following link:
Configuring the Web.config file
2.
3. When it is time to deploy your application there is an additional step you need to perform.
You have to ensure that the above referenced assemblies (in your Web.config files) are
present in the GAC.

2.1.2 Fast Deployment Pattern


Follow the steps below to deploy the application in the development server by referencing the
DLL in the application's Bin folder.

1. Delete the Syncfusion assembly GAC entries in your development machine. The
referenced assemblies will be copied over to the Bin folder.
2. The Web.config file should be configured according to the referenced DLLs. For more
information on the Web.config file configuration please refer to the following link:
Configuring Web.Config file

Note: If you do not want to delete Syncfusion assembly GAC entries then in the Web.config file
please remove the Culture, Version, and PublicKeyToken attributes used in all <assemblies>,
<httpHandlers>, and <handlers> nodes.

2.1.3 DLL
The following assemblies need to be referenced in your application in order to use Essential Grid
for ASP.NET MVC.
 Syncfusion.Core.dll
 Syncfusion.Grid.Mvc.dll
 Syncfusion.Linq.Base.dll
 Syncfusion.Shared.Mvc.dll
 Syncfusion.Compression.Base.dll
 Syncfusion.XlsIO.Mvc.dll
 Syncfusion.DocIO.Mvc.dll

© 2014 Syncfusion. All rights reserved. 24 | Page


Essential Grid for ASP.NET MVC Classic

 Syncfusion.Pdf.Base.dll
 AjaxMin.dll
 Syncfusion.Theme.Base.dll

Note: Theme source is included from Essential Studio version 10.3.0.43. Therefore, reference of
“Syncfusion.Theme.Base” dll must be included in applications to load themes for the controls.

2.2 Samples and Location

This section covers the location of the installed samples and describes the procedure to run the
samples through the sample browser and online. It also provides the location of the source code.

Samples Installation Location


The Grid MVC samples are installed in the following location, locally on the disk:

<Install Location>\Syncfusion\EssentialStudio\<Version
Number>\MVC\Grid.MVC\Samples\3.5

Viewing Samples

To view the samples, follow the steps below:

1. Click Start>All Programs>Syncfusion>Essential Studio <version number>


>Dashboard. The Syncfusion Essential Studio Dashboard <version number> window
is displayed.

© 2014 Syncfusion. All rights reserved. 25 | Page


Essential Grid for ASP.NET MVC Classic

Figure 2: Syncfusion Essential Studio Dashboard

In the Dashboard window, click ASP.NET MVC in the Essential Studio panel and click Run
Local Samples. The ASP.NET MVC Sample Browser window is displayed.

Note: You can view the samples in any of the following three ways:

1. Run Samples—Click to view the online samples.


2. Run Local Samples—Click to view locally installed samples.
3. Explore Samples—Explore ASP.NET MVC samples on disk.

Click Grid in the other ASP.NET MVC products. The Grid samples are displayed.

© 2014 Syncfusion. All rights reserved. 26 | Page


Essential Grid for ASP.NET MVC Classic

Figure 3: Grid Samples Displayed in the ASP.NET MVC Sample Browser

Select any sample and browse through its features.

Source Code Location

The default location of the Essential Grid for MVC source code is:

[System Drive]:\Program Files\Syncfusion\Essential Studio\[Version


Number]\MVC\Grid.MVC\Src

© 2014 Syncfusion. All rights reserved. 27 | Page


Essential Grid for ASP.NET MVC Classic

3 Getting Started
3.1 Getting Started with the Syncfusion MVC Grid

The Syncfusion MVC Grid is a full-featured Grid control built specifically for ASP.NET MVC.
Integrating the Grid into your application involves making configuration changes and adding the
required code into your application controllers and views. This document will provide the
necessary information for this and also explain the changes as needed.
Syncfusion provides two utilities that can help you with integrating the Grid into your MVC
application:
1. Project creation template utility
2. Project migration utility
Both of the above utilities are integrated into Visual Studio 2010 and 2012. We will be reviewing
these utilities in the document as well, but the focus will be on the manual changes that need to
be made to the application project as these utilities only automate making these changes.

3.1.1 Syncfusion Utilites


3.1.1.1 Project Template Utility
3.1.1.1.1 Creating an MVC4 Razor application with the Syncfusion Project Template

Configuration of the MVC project to enable the Syncfusion Grid can be done using the Syncfusion
Project Template utility.
Create a new MVC project:

1. In the File menu in Visual Studio, click New Project.


2. The New Project dialog box is displayed.

© 2014 Syncfusion. All rights reserved. 29 | Page


Essential Grid for ASP.NET MVC Classic

Figure 4: New Project Dialog box opened.

3. In the Templates panel, expand the Syncfusion list and then click Web.
4. Select Syncfusion ASP.NET MVC 4 Web Application (C#) in the main window.
5. Enter an appropriate application name. The Syncfusion Product Selection dialog box is
displayed.

© 2014 Syncfusion. All rights reserved. 30 | Page


Essential Grid for ASP.NET MVC Classic

Figure 5: Syncfusion Product Selection dialog opened


6. Select the Grid check box under the Desktop tab. This will create a new MVC application
with all the predefined settings (which were called in the steps of configuration phase).
7. Click Next. The Syncfusion Theming dialog box is displayed.

© 2014 Syncfusion. All rights reserved. 31 | Page


Essential Grid for ASP.NET MVC Classic

Figure 6: Syncfusion theming dialog opened

8. Select a theme.
9. Click Done. Now the application is ready to be added to the Syncfusion MVC Grid as
explained in the section “Adding Grid to the project”.
2.

© 2014 Syncfusion. All rights reserved. 32 | Page


Essential Grid for ASP.NET MVC Classic

3.1.1.2 Project Migration Utility


3.1.1.2.1 Converting an existing MVC application to a Syncfusion MVC application
Syncfusion also provides a utility to convert an existing ASP.NET MVC application so that it is
Syncfusion MVC enabled.

1. Right click on the project.

Figure 7: Project Menu opened

2. Select Syncfusion VS Extension.


3. Select Convert to Syncfusion MVC Application.

The Syncfusion Product Selection dialog box is displayed.

© 2014 Syncfusion. All rights reserved. 33 | Page


Essential Grid for ASP.NET MVC Classic

Figure 8: Syncfusion Product Selection dialog opened

4. Select the Grid check box under the Desktop tab.


5. Click Next. The Syncfusion Theming dialog box is displayed.

© 2014 Syncfusion. All rights reserved. 34 | Page


Essential Grid for ASP.NET MVC Classic

Figure 9: Syncfusion theming dialog opened

6. Select a theme.

7. Now the application is ready for adding the Syncfusion MVC Grid as explained in the
following section, “Adding Grid to the project”.

3.1.2 Adding Grid to the project

The Grid requires a model for binding the data. Please create a model and add it into the
application (Refer to How to > Adding a Model to the Application).

The Syncfusion MVC Grid can be added to a View. The next step would be to create a create a
strongly typed view (Refer to How to > Strongly Typed View).

© 2014 Syncfusion. All rights reserved. 35 | Page


Essential Grid for ASP.NET MVC Classic

The code below shows how the Grid can be instantiated in the View and bound to the Model.

Razor:

Index.cshtml
@{Html.Syncfusion().Grid<EditableOrder>("OrderGrid")
.Caption("Orders")
.Datasource(Model)
.ActionMode(ActionMode.Server)
.EnablePaging()
.EnableGrouping()
.EnableSorting()
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID");
column.Add(p => p.ShipCity).HeaderText("ShipCity");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
column.Add(p => p.Verified).HeaderText("Verified");

}).Render();
}

ASPX:

Index.aspx
<%=Html.Syncfusion().Grid< EditableOrder >("SampleGrid")
.Datasource(Model)
.EnablePaging()
.ActionMode(ActionMode.Server)
.EnableSorting()
.Caption("Orders")

.Column(column =>

© 2014 Syncfusion. All rights reserved. 36 | Page


Essential Grid for ASP.NET MVC Classic

{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID");
column.Add(p => p.ShipCity).HeaderText("ShipCity");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
column.Add(p => p.Verified).HeaderText("Verified");

}) %>

The last step in adding Grid to the project is to add two action methods in the HomeController
(one for loading the view and one for handling the grid paging and sorting actions). The action
methods populate the Model created and pass them to the View.

public ActionResult Index()


{
IEnumerable data = OrderRepository.GetAllRecords();
return View(data);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();

© 2014 Syncfusion. All rights reserved. 37 | Page


Essential Grid for ASP.NET MVC Classic

Figure 10: Grid with data

Sample links:
VS 2012/ MVC4 / Razor sample: sample-vs2012.zip
VS2010/ MVC4 / Razor sample: sample-vs2010.zip

© 2014 Syncfusion. All rights reserved. 38 | Page


Essential Grid for ASP.NET MVC Classic

4 Concepts and Features

This section discusses all the concepts and features of the Grid control under the following sub-
sections. All the topics provide you with complete information about the concepts and give you
the step-by-step procedures involved while working with the MVC architecture.
Reference
You can refer to the installation samples at the following location. Individual samples are available
for every concept.
<Install Location>\Syncfusion\EssentialStudio\<Version Number>\MVC\Grid.MVC\Samples\3.5

4.1 Action Modes

The Grid control handles data presentation operations like paging, grouping, filtering, editing and
sorting, or you can perform those operations. But this mode of action for the Grid control is
decided using the ActionMode property whose options are described in the following table.
Essential Grid supports two kinds of action modes.
Properties
Property Description Type of Value it accepts
property
ActionMode Used to set the action mode of the control. Enum ActionMode.Server
Server—All the operations like (or)
sorting,filtering, editing, paging, and grouping
are handled by Essential Grid itself (by ActionMode.JSON
default).
JSON (JavaScript Object Notation)—User
has to handle the operations. The only
possible operations are paging, filtering,
editing, grouping, and sorting.

Methods
Method Parameters Return type Descriptions
ActionMode(ActionMode actionMode IGridBuilder<T> Used to set the
actionMode) action mode to
control.

© 2014 Syncfusion. All rights reserved. 39 | Page


Essential Grid for ASP.NET MVC Classic

4.1.1 Server Mode


Essential Grid for ASP.NET MVC will perform service-side requests (HTTP POST) when doing
paging, sorting, grouping, and filtering actions. This is called “server binding.”
For the first request, bind the grid with data using the Datasource property and render the view.
For subsequent paging, sorting, and filtering actions you need to write a post action method in
your controller. The grid is fully AJAX enabled, so while calling grid actions such as paging,
sorting, and filtering, the entire view won’t be rendered. It just calls the GridHtmlActionResult to
update the grid.
This can be achieved in the following ways.

4.1.1.1 Through GridBuilder


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() in order to bind the data
source.

View [ASPX]

<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid")
.Datasource(Model)
.EnablePaging()
.EnableSorting()
.ActionMode(ActionMode.Server)
.Column( column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
%>

View [cshtml]

@{
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Flat
Grid")
.Datasource(Model)
.EnablePaging()
.EnableSorting()
.ActionMode(ActionMode.Server)
.Column( column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");

© 2014 Syncfusion. All rights reserved. 40 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(c => c.EmployeeID).HeaderText("Employee


ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
}).Render();
}

4. Set its data source and render the view.


Controller

/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.Take(200);
return View(data);
}

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.

Controller

/// <summary>
/// Paging/sorting Requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}

6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 41 | Page


Essential Grid for ASP.NET MVC Classic

Figure 11: Grid with Data

4.1.1.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid","GridModel",
column => {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c =>
c.Freight).HeaderText("Freight");
}) %>

© 2014 Syncfusion. All rights reserved. 42 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("FlatGrid","G
ridModel",
column =>{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");

}))

4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from controller to view using the ViewData class as shown below:

public ActionResult Index()


{
GridPropertiesModel<Order> model = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200),
AllowPaging = true,
AllowSorting = true,
ActionMode = ActionMode.Server
};
ViewData["GridModel"] = model; // pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller

/// <summary>
/// Paging/sorting Requests are mapped to this method. This method
invokes the HtmlActionResult
/// from the Grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]

© 2014 Syncfusion. All rights reserved. 43 | Page


Essential Grid for ASP.NET MVC Classic

public ActionResult Index(PagingParams args)


{
IEnumerable data = new NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}
6. Run the application. The grid will appear as shown below.

Figure 12: Grid with Data

4.1.2 JSON Mode

JSON (JavaScript Object Notation) is a lightweight data interchange format for serialization of
structured data. It defines a small set of formatting rules for the portable representation of
structured data. It is human readable, platform independent, and has a wide availability of
implementations. You will use this JSON format to exchange data in the MVC architecture.
In JSON mode, the only possible operations are paging, filtering, editing, grouping, and sorting.
Operation in the JSON mode can be handled by you. The PagingParams instance holds the
essential information about the current request. ASP.NET client-side templates have the
responsibility of generating HTML from JSON. This mode gives better performance than the
server mode. The initial rendering is done in the server mode only.

4.1.2.1 Through GridBuilder

1. Create a model in the application (refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (refer to How to > Strongly Typed View).

© 2014 Syncfusion. All rights reserved. 44 | Page


Essential Grid for ASP.NET MVC Classic

3. Create the Grid control in the view and configure its properties.
4. Set action mode as JSON using the ActionMode method.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("JsonGrid")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Column(column => {
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(P => P.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("JsonGrid")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Column(column => {
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(P => P.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
}).Render();

5. Render the view.


Controller
public ActionResult Index()
{
return View();
}

6. In order to work with paging and sorting, create a post method for index actions and bind the
data source to the grid as given in the following code sample.

© 2014 Syncfusion. All rights reserved. 45 | Page


Essential Grid for ASP.NET MVC Classic

Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

7. Run the application. The following output is displayed.

Figure 13: Grid with JSON ActionMode

4.1.2.2 Through GridPropertiesModel

3. 1. Create a model in the application (refer to How to > Adding a Model to the Application).
4. 2. Create a strongly typed view (refer to How to > Strongly Typed View).
5. 3. Create the Grid control in the view and configure its properties.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("JsonGrid","GridModel",column => {
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(P => P.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
})%>

© 2014 Syncfusion. All rights reserved. 46 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@( Html.Syncfusion().Grid<Order>("JsonGrid","GridModel",column => {
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(P => P.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
}) )

4. Create a GridPropertiesModel in the Index method. Specify the ActionMode as


ActionMode.JSON.
Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> model = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders.Take(200).
ToList(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
ActionMode = ActionMode.JSON
};
ViewData["GridModel"] = model;
return View();
}

5. In order to work with paging and sorting, create a Post method for Index actions and bind the
data source to the grid as given in the following code sample.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridJSONActions<Order>();
}

6. Run the application. The following output is displayed:

© 2014 Syncfusion. All rights reserved. 47 | Page


Essential Grid for ASP.NET MVC Classic

Figure 59: Grid with JSON Action Mode

4.2 Data Binding


This section explains how to bind a data source to the Grid control. It includes the following
topics:
 LINQ to SQL data source
 ADO.NET Entity Model data source
 Generic collection

The following table contains some data binding properties and their corresponding descriptions:
Property
Property Description Type of Value it Any other
property accepts dependencies/sub-
properties associated
DataSource Gets or sets IEnumerable Any NA
DataSource for the IEnumerable
Grid control data.

Method
Method Parameters Return type Descriptions
Datasource IEnumerable IGridBuilder<T> Used to set data source to
(IEnumerable<T>) datasource the Grid control.

© 2014 Syncfusion. All rights reserved. 48 | Page


Essential Grid for ASP.NET MVC Classic

4.2.1 LINQ to SQL Data Source


LINQ to SQL is a component of .NET Framework version 3.5 that provides a run-time
infrastructure for managing relational data as objects.
LINQ to SQL allows .NET developers to write “queries” in their .NET language of choice to
retrieve and manipulate data from a SQL Server database. In a general sense, LINQ to SQL
allows you to create SQL queries in our preferred .NET language syntax and work with a strongly
typed collection of objects as a return result. You can make changes to these objects and then
you can save changes back to the database.
LINQ to SQL fully supports transactions, views, and stored procedures. It also provides an easy
way to integrate data validation and business logic rules into your data model.
For more information on LINQ to SQL see http://msdn.microsoft.com/en-
us/library/bb386976%28v=VS.100%29.aspx

4.2.1.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() in order to bind the data
source.

View [ASPX]

<%=Html.Syncfusion().Grid<Product>("Product_grid")
.Datasource(Model)
.Caption("Products")
.Column( column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.ProductName).HeaderText("Product Name");
column.Add(P =>
P.QuantityPerUnit).HeaderText("Quantity Per Unit");
column.Add(p =>
p.SupplierID).HeaderText("Supplier ID");

})
.EnablePaging()
.EnableSorting()
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Product>("Product_grid")
.Datasource(Model)
.Caption("Products")
.Column( column =>
{
column.Add(p =>

© 2014 Syncfusion. All rights reserved. 49 | Page


Essential Grid for ASP.NET MVC Classic

p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.ProductName).HeaderText("Product Name");
column.Add(P =>
P.QuantityPerUnit).HeaderText("Quantity Per Unit");
column.Add(p =>
p.SupplierID).HeaderText("Supplier ID");

})
.EnablePaging()
.EnableSorting()
Render();
}

4. Set its data source and render the view.


Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Products;
return View(data);
}

5. In order to work with paging andsorting actions, create a Post method for Index actions and
bind the data source to the grid as shown in the following code.
Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Products;
return data.GridActions<Order>();
}

6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 50 | Page


Essential Grid for ASP.NET MVC Classic

Figure 14: LINQ to SQL Grid

4.2.1.2 Through GridPropertiesModel

1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]

<%=Html.Syncfusion().Grid<Product>("Product_Grid","GridMode
l", column=> {
column.Add(p => p.ProductID).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.QuantityPerUnit).HeaderText("Quantity Per Unit");
column.Add(p => p.SupplierID).HeaderText("Supplier
ID");
})%>

View [cshtml]

@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Product_Grid
","GridModel",
column=> {
column.Add(p => p.ProductID).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.QuantityPerUnit).HeaderText("Quantity Per Unit");

© 2014 Syncfusion. All rights reserved. 51 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p => p.SupplierID).HeaderText("Supplier


ID");
}))

4. Create a GridPropertiesModel in the Index method. Bind the data source using the
Datasource property and pass the model from controller to view using the ViewData class
as shown in the following code.
public ActionResult Index()
{
GridPropertiesModel<Product> model = new
GridPropertiesModel<Product>()
{
DataSource=new NorthwindDataContext().Products,
Caption="Product",
AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as given in the code below.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Products;
return data.GridActions<Product>();
}

6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 52 | Page


Essential Grid for ASP.NET MVC Classic

Figure 15: LINQ to SQL Grid


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > LINQ-to-SQL

4.2.2 ADO.NET Entity Model Data Source

The Entity Framework supports an Entity Data Model (EDM) for defining data at both the storage
and conceptual level and also mapping between the two. It also enables you to program directly
against the data types defined at the conceptual level as common language runtime (CLR)
objects. The Entity Framework provides tools to generate an EDM and the related CLR objects
based on an existing database. This reduces much of the data access code that is required to
create object-based data application and services. This makes it faster to create object-oriented
data applications and services from an existing database.

The Entity Framework enables you to avoid the tedious work of building your data access classes
by hand. Entity Framework applications can run on any computer on which the .NET Framework
3.5 Service Pack 1 (SP1) is installed.

For details, see: http://msdn.microsoft.com/en-in/library/bb399567(v=VS.90).aspx


http://msdn.microsoft.com/en-in/library/bb896338%28v=VS.90%29.aspx

Most applications are currently written on top of relational databases. At some point, these
applications will have to interact with the data represented in a relational form.Database schemas
are not always ideal for building applications and the conceptual models of applications differ
from the logical models of databases. The Entity Data Model (EDM) is a conceptual data model
that can be used to model the data of a particular domain so that applications can interact with
data as entities or objects.

© 2014 Syncfusion. All rights reserved. 53 | Page


Essential Grid for ASP.NET MVC Classic

Properties
Property Description Type of Value it Any other
property accepts dependencies/sub-
properties
associated
DataSource Gets or sets IEnumerable Any None
the data source IEnumerable
for the Grid data.
control.

Methods

Method Description Parameters Return type


Datasource (IEnumerable<T>) Used to set a data IEnumerable data IGridBuilder<T>
source to the Grid source
control.

4.2.2.1 Through GridBuilder

Data can be bound by customizing the view. To do so, there are the six steps involved:
1. Create an Entity model in an application (see Creating the ADO.NET Entity Data Model).
2. Create a strongly typed view (see Creating a Strongly Typed View).
3. In the view, use the Model property in Datasource to bind the data source.

View [ASPX]

<%=Html.Syncfusion().Grid<employee>("EntityGrid")
.Datasource(Model)
.Caption("Employee Details")
.AutoFormat(Skins.Sandune)
.EnablePaging()
.EnableSorting()
.Column(cols =>
{
cols.Add(c => c.emp_id).HeaderText("Employee ID");
cols.Add(c => c.fname).HeaderText("First Name");
cols.Add(c => c.lname).HeaderText("Last Name");
cols.Add(c => c.minit).HeaderText("Min");
cols.Add(c => c.hire_date).HeaderText("Ship
City").Format("{hire_date:dd/mm/yyyy}");
})
%>

© 2014 Syncfusion. All rights reserved. 54 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<employee>("EntityGrid")
.Datasource(Model)
.Caption("Employee Details")
.AutoFormat(Skins.Sandune)
.EnablePaging()
.EnableSorting()
.Column(cols =>
{
cols.Add(c => c.emp_id).HeaderText("Employee ID");
cols.Add(c => c.fname).HeaderText("First Name");
cols.Add(c => c.lname).HeaderText("Last Name");
cols.Add(c => c.minit).HeaderText("Min");
cols.Add(c => c.hire_date).HeaderText("Ship
City").Format("{hire_date:dd/mm/yyyy}");
}).Render();
}

4. Set the data source and render the view.

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new PUBSEntities().employees;
return View(data);
}

5. In order to work with paging and sorting actions, create a Post method for the Index actions
and bind the data source to the grid, as seen in the code below.

Controller

/// <summary>
/// Sorting/paging requests are mapped to this method.
/// This method invokes the HtmlActionResult from the grid.
/// The required response is generated.
/// </summary>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{

© 2014 Syncfusion. All rights reserved. 55 | Page


Essential Grid for ASP.NET MVC Classic

IEnumerable data = new PUBSEntities().employees;


return data.GridActions<employee>();
}

6. Run the application; the grid will then appear as seen in the following image.

Figure 16: Entity Model Grid

4.2.2.2 Through GridPropertiesModel

Data can be bound by using the GridPropertiesModel. To do so, there are five steps involved:
1. Create an Entity model in the application (see Creating the ADO.NET Entity Data Model).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create a grid control in the view by adding the following code in the Index.aspx file.
View [ASPX]

<%=Html.Syncfusion().Grid<employee>("EntityGrid","GridModel", column =>


{
column.Add(c => c.emp_id).HeaderText("Employee ID");
column.Add(c => c.fname).HeaderText("First Name");
column.Add(c => c.lname).HeaderText("Last Name");
column.Add(c => c.minit).HeaderText("Min");
column.Add(c => c.hire_date).HeaderText("Ship
City").Format("{hire_date:dd/mm/yyyy}"); })
%>

View [cshtml]

© 2014 Syncfusion. All rights reserved. 56 | Page


Essential Grid for ASP.NET MVC Classic

@( Html.Syncfusion().Grid<employee>("EntityGrid","GridModel", column =>


{
column.Add(c => c.emp_id).HeaderText("Employee ID");
column.Add(c => c.fname).HeaderText("First Name");
column.Add(c => c.lname).HeaderText("Last Name");
column.Add(c => c.minit).HeaderText("Min");
column.Add(c => c.hire_date).HeaderText("Ship
City").Format("{hire_date:dd/mm/yyyy}");
}))

4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from controller to view using the ViewData class.

public ActionResult Index()


{
// Create object to GridPropertiesMode.
// Set the required properties.
GridPropertiesModel<employee> model = new
GridPropertiesModel<employee>()
{
DataSource = new PUBSEntities().employees,
Caption="Employee Details",
AutoFormat=Skins.Sandune,
AllowPaging=true,
AllowSorting=true
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with paging and sorting actions, create a Post method for the Index actions
and bind the data source to the grid.

Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new PUBSEntities().employees;
return data.GridActions<employee>();

© 2014 Syncfusion. All rights reserved. 57 | Page


Essential Grid for ASP.NET MVC Classic

6. Run the application; the grid will then appear as seen in the following image.

Figure 17: Entity Model Grid


Sample Link
To view the samples, follow these steps:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > Entity FrameWork

4.2.3 Generic Collections


This section demonstrates the implementation of a generic collection and how you can bind it to
the Grid control.
A generic collection is one that can handle any data type in a generic and type-safe manner. By
creating a generic collection, you can get the immediate benefit of type safety without having to
derive from a base collection type and implement type-specific members.

4.2.3.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Creating the Generic Collection Model).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource in order to bind the data source.
View [ASPX]

© 2014 Syncfusion. All rights reserved. 58 | Page


Essential Grid for ASP.NET MVC Classic

<%=Html.Syncfusion().Grid<Student>("StudentGrid")
.Datasource(Model)
.Caption("Student List")
.EnablePaging()
.EnableSorting()
.Column( column => {
column.Add(p => p.UniversityCode).HeaderText("University
Code");
column.Add(p => p.Title).HeaderText("Course Title");
column.Add(P => P.Duration).Format("{Duration} hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Student>("StudentGrid")
.Datasource(Model)
.Caption("Student List")
.EnablePaging()
.EnableSorting()
.Column( column => {
column.Add(p => p.UniversityCode).HeaderText("University
Code");
column.Add(p => p.Title).HeaderText("Course Title");
column.Add(P => P.Duration).Format("{Duration} hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
}).Render();
}

4. Set its data source and render the view.

Controller

/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
var data = new StudentDataContext().Student.Take(200);
return View(data);
}

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the code below.

© 2014 Syncfusion. All rights reserved. 59 | Page


Essential Grid for ASP.NET MVC Classic

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().Student.Take(200);
return data.GridActions<Student>();
}

6. Run the application. The grid will appear as shown below.

Figure 18: Generic Collection Grid

4.2.3.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]

<%=Html.Syncfusion().Grid<Student>("StudentGrid", "GridModel",
column =>
{
column.Add(p =>
p.UniversityCode).HeaderText("University Code");

© 2014 Syncfusion. All rights reserved. 60 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p => p.Title).HeaderText("Course


Title");
column.Add(P => P.Duration).Format("{Duration}
hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
}) %>

View [cshtml]

@( Html.Syncfusion().Grid<Student>("StudentGrid", "GridModel",
column =>
{
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p => p.Title).HeaderText("Course
Title");
column.Add(P => P.Duration).Format("{Duration}
hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
}))

4. Create a GridPropertiesModel in the Index method. Bind the data source using the
Datasource property and pass the model from controller to view using the ViewData class
as given below.
public ActionResult Index()
{
GridPropertiesModel<Student> model = new
GridPropertiesModel<Student>()
{
DataSource = new StudentDataContext().Student.Take(200),
Caption = "Student List",
AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller

© 2014 Syncfusion. All rights reserved. 61 | Page


Essential Grid for ASP.NET MVC Classic

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().Student.Take(200);
return data.GridActions<Student>();
}

6. Run the application. The grid will appear as shown below.

Figure 19: Generic Collection Grid


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > Generic List Binding

4.2.4 Unbound Column


The data you display in the Grid control will normally come from a data source of some kind, but
you might want to display a column of data that does not come from the data source. This kind of
column is called an unbound column.
Unbound columns are used to display custom content in the grid. For example, if you want to
display some new columns like buttons or links to other parts of the grid, this feature will be
useful.

© 2014 Syncfusion. All rights reserved. 62 | Page


Essential Grid for ASP.NET MVC Classic

Essential Grid supports adding unbound column through IRootGridColumnBuilder in the view.
While using unbound columns you will be unable to perform sorting, grouping, and filtering
functionalities.

Methods

Method Descriptions Parameters Return type


Add() Used to add unbound column string IRootColumnBuilder<T>
to grid control

UnBound() Used to convert the bound to No parameter IColumnBuilder<T>


Unbound

4.2.4.1 Through GridBuilder

1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource to bind the data source.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Render();
}

4. Specify the visible column collection using ColumnBuilder actions as follows.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Column( column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");

© 2014 Syncfusion. All rights reserved. 63 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p => p.ShipCountry).HeaderText("Ship


Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
})
%>
View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Column( column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
}).Render();
}

5. In column mapping, add the unbound column using the Add(string) method. In this case a
“Delete” column has been added as an unbound column which is used to delete records in
the grid.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Column( column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
column.Add("Delete").HeaderText("Delete
Record").Format("<a class=\"TemplateCell\"
href=\"DeleteRecord?id={OrderID}\">Delete</a>");
})

© 2014 Syncfusion. All rights reserved. 64 | Page


Essential Grid for ASP.NET MVC Classic

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders Grid")
.Column( column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
column.Add("Delete").HeaderText("Delete
Record").Format("<a class=\"TemplateCell\"
href=\"DeleteRecord?id={OrderID}\">Delete</a>");
}).Render();
}

6. Add two methods (one for loading the view and one for handling the delete actions).
Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.Take(15);
return View(data);
}

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult DeleteRecord(int id)
{
NorthwindDataContext context = new NorthwindDataContext();
Order order = (Order)context.Orders.Single(p => p.OrderID
== id);
context.Orders.DeleteOnSubmit(order);
context.SubmitChanges();
return RedirectToAction("Index");
}

7. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 65 | Page


Essential Grid for ASP.NET MVC Classic

Figure 20: Grid with Unbound Column

4.2.4.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the grid in the view and create visible a column collection using
IRootColumnBuilder<T> as shown below.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("UnBoundColumn_Grid", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("UnBoundColumn_Grid", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
}))

© 2014 Syncfusion. All rights reserved. 66 | Page


Essential Grid for ASP.NET MVC Classic

4. In column mapping, add the unbound column using the Add(string) method. In this case a
“Delete” column has been added as an unbound column which is used to delete records in
the grid.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("UnBoundColumn_Grid", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
column.Add("Delete").HeaderText("Delete
Record").Format("<a class=\"TemplateCell\"
href=\"DeleteRecord?id={OrderID}\">Delete</a>");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("UnBoundColumn_Grid", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{Freight:c}");
column.Add("Delete").HeaderText("Delete
Record").Format("<a class=\"TemplateCell\"
href=\"DeleteRecord?id={OrderID}\">Delete</a>");
}))

5. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from controller to view using the ViewData class as given below.

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order> ()
{
DataSource = new
NorthwindDataContext().Orders.Take(15),
Caption = "Orders"
};
ViewData["GridModel"] = gridModel; // Pass the model from

© 2014 Syncfusion. All rights reserved. 67 | Page


Essential Grid for ASP.NET MVC Classic

controller to view using ViewData.


return View();
}

6. Create a Delete action method which is used to delete the record from the database. This is
shown int he following code sample.

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult DeleteRecord(int id)
{
NorthwindDataContext context = new
NorthwindDataContext();
Order order = (Order)context.Orders.Single(p =>
p.OrderID == id);
context.Orders.DeleteOnSubmit(order);
context.SubmitChanges();
return RedirectToAction("Index");
}

7. Run the application. The grid will appear as shown.

Figure 21: Grid with Unbound Column


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Getting Started > Unbound Column

4.2.5 Data binding support for drop-down lists in columns


Drop-down lists in grid columns provide extensive data binding support so that the column items
can be mapped to the DropDownDataSource property.
The following table explains the supported overload methods in Server and JSON mode.

© 2014 Syncfusion. All rights reserved. 68 | Page


Essential Grid for ASP.NET MVC Classic

Method Server Mode JSON Mode

DropDownDataSource(IEnumerable Supported Supported


dropDownDataSource)

DropDownDataSource(IEnumerable Supported Supported


dropDownDataSource, string
dataTextField, string
dataValueField)

DropDownDataSource(Array data) Supported Supported

DropDownDataSource(string Not Supported Supported


actionName)

DropDownDataSource(string Not Supported Supported


actionName, string dataTextField,
string dataValueField)

Use Case Scenarios


The data binding feature helps users plug in data from a data source to a drop-down list.

4.2.5.1 Properties
Table 3: Property Table

Property Description Type Value it accepts Reference links

DropDownDataSo Gets or sets the data Server-side Any IEnumerable CellEditType.Drop


urce source, which is used data, DownEdit
to populate drop-down
String,
lists with column items.
Any array data.

4.2.5.2 Methods
Table 4: Methods Table

Method Description Parameters Return Type Reference


links

© 2014 Syncfusion. All rights reserved. 69 | Page


Essential Grid for ASP.NET MVC Classic

DropDownD Gets or sets the data Overloads: IGridColumn CellEditTyp


ataSource source, which is used Builder<T> e.DropDow
to populate drop-down 1. (IEnumerable
nEdit
lists with column items. dropDownDataSource)
2. (IEnumerable
dropDownDataSource, string
dataTextField, string
dataValueField)
3. (string actionName)
4. (string actionName, string
dataTextField, string
dataValueField)
5. (Array data)

Sample Link

To view the samples, follow the steps below:


1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Server Mode

4.2.5.3 Data binding support


The following methods are used to bind the data for drop-down lists in columns:
1. Bind drop-down data using the Enumerable method.
2. Bind drop-down data using the Action Mapper method.
3. Bind drop-down data using the Array method.

4.2.5.3.1 Bind drop-down data using the Enumerable method


There are two overload methods available under the Enumerable type. The following overload
methods are supported in both server and JSON mode:
1. Enumerable data
2. Enumerable data with text and value fields

4.2.5.3.1.1 Enumerable data

The DropDownDataSource method can be configured in two ways:

1. Through GridBuilder
2. Through GridPropertiesModel

4.2.5.3.1.1.1 Through GridBuilder

© 2014 Syncfusion. All rights reserved. 70 | Page


Essential Grid for ASP.NET MVC Classic

The steps to configure the data binding support for drop-down column features using
GridBuilder are:
1. Create a model in the application. Refer to How to>Adding a Model to the Application and
Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete.
5. Essential Grid allows adding new records through grid toolbar items. Refer to Concepts and
Features > Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and Features >
Editing.
View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((System.Collections.IEnumerable)
ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")

.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((System.Collections.IEnumerable)

© 2014 Syncfusion. All rights reserved. 71 | Page


Essential Grid for ASP.NET MVC Classic

ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})

.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}

7. In the controller, pass the IEnumerable data to the drop-down ViewData.

Controller

public ActionResult Index()


{
ViewData["DropDownSource"] = DropDown;
var data = OrderRepository.GetAllRecords();
return View(data);
}

public IEnumerable DropDown


{
get
{
IEnumerable data = new
NorthwindDataContext().Employees.Select(emp=>emp.FirstName);
return data;
}
}
6.
8. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to the
repository action method given below.
7.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used for inserting records into
the data source.
OrderRepository.Add(ord);
//After adding the record into database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

© 2014 Syncfusion. All rights reserved. 72 | Page


Essential Grid for ASP.NET MVC Classic

Note: Refer to the repository action codes from Editing>OrderRepository Class.


9. In the controller, create a method to save changes. In this example, the repository method
Update() is used to update records to the data source.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh


the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

10. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() will delete the record from the data
source.
Controller

/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);

// After deleting refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
11. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 73 | Page


Essential Grid for ASP.NET MVC Classic

Figure 22: Grid with toolbar options for Editing, Inserting, and Deleting records

12. Edit any row. The grid will appear as shown below.

Figure 23: Data binding support for the CustomerID column in the grid

4.2.5.3.1.1.2 Through GridPropertiesModel


The steps for configuring the data binding support for drop-down column features using the
GridPropertiesModel are:

1. Create a model in the application. Refer to How to>Adding a Model to the


Application and Editing>EditableOrder Class.
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

© 2014 Syncfusion. All rights reserved. 74 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((System.Collections.IEnumerable)
ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>

View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((System.Collections.IEnumerable)
ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
)

4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};

© 2014 Syncfusion. All rights reserved. 75 | Page


Essential Grid for ASP.NET MVC Classic

ViewData["DropDownSource"] = DropDown;
ViewData["GridModel"] = model; // Pass the model from the
controller to the view using ViewData.

5. In the controller, pass the IEnumerable data to the dropdown ViewData.

Controller

public IEnumerable DropDown


{
get
{
IEnumerable data = new
NorthwindDataContext().Employees.Select(emp=>emp.FirstName);
return data;
}
}

6. Enable editing using the Editing property in the GridPropertiesModel and


configure the editing properties, such as AllowNew, AllowEdit, and AllowDelete.
7. Specify the grid editing mode using the EditMode property.
8. Specify the Primary property which uniquely identifies the grid record.
9. Add the edit setting to the model.
10. Essential Grid allows adding new records using grid toolbar items. Refer to
Concepts and Features>Editing.
11. In the controller, create a method to add new records to the grid as shown below. In
this example, the repository method Add() is being created to insert records in the
database. Refer to the repository action method given in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used for inserting records
into the data source.
OrderRepository.Add(ord);

//After adding the record into the database, refresh the


grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

© 2014 Syncfusion. All rights reserved. 76 | Page


Essential Grid for ASP.NET MVC Classic

Note: Refer to the repository action codes in Editing>OrderRepository Class.

12. In the controller, create a method to save changes, as shown in the following code.
In this example, the repository method Update() is used to update records in the
data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update used to update the records
into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh the
grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

13. In the controller, create a method to delete the records from the database as
displayed below.

In this example, the repository action Delete() will delete the record from the data source.

Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

14. Run the application. The grid will appear as shown in the following screenshot.

© 2014 Syncfusion. All rights reserved. 77 | Page


Essential Grid for ASP.NET MVC Classic

Figure 24: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

15. Edit any row. The grid will appear as shown below.

Figure 25: Data binding support for CustomerID column in the grid

4.2.5.3.1.2 Enumerable data with text and value field

The DropDownDataSource can be configured in two ways:

1. Through GridBuilder
2. Through GridPropertiesModel

4.2.5.3.1.2.1 Through GridBuilder

© 2014 Syncfusion. All rights reserved. 78 | Page


Essential Grid for ASP.NET MVC Classic

The steps to configure the data binding support for drop-down column features using
GridBuilder are:

1. Create a model in the application. Refer to How to>Adding a Model to the Application
and Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing by using the Editing method and configure the editing properties such
as AllowNew, AllowEdit, and AllowDelete.
5. Essenital Grid allows adding new records through grid toolbar items. Refer to
Concepts and Features>Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and
Features>Editing.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource(System.Collections.IEnumerable)ViewData["DropDownSo
urce"], "Name", "StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource(System.Collections.IEnumerable)ViewData["DropDownSo
urce"], "Name", "StudentID");
column.Add(p => p.Verified).HeaderText("Verified");

© 2014 Syncfusion. All rights reserved. 79 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p => p.ShipRegion).HeaderText("Ship Region");


column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>

7. In the controller, pass the IEnumerable data to the ViewData.

Controller

public ActionResult Index()


{
ViewData["DropDownSource"] = DropDown;
var data = OrderRepository.GetAllRecords();
return View(data);
}

public IEnumerable DropDown


{
get
{
Student[] s = new Student[10];
s[0] = new Student() { Name = "Nancy", StudentID = 1 };
s[1] = new Student() { Name = "Andrew", StudentID = 2 };
s[2] = new Student() { Name = "Janet", StudentID = 3 };
s[3] = new Student() { Name = "Margaret", StudentID = 4 };
s[4] = new Student() { Name = "Steven", StudentID = 5 };
s[5] = new Student() { Name = "Michael", StudentID = 6 };
s[6] = new Student() { Name = "Robert", StudentID = 7 };
s[7] = new Student() { Name = "Laura", StudentID = 8 };
s[8] = new Student() { Name = "Anne", StudentID = 9 };
s[9] = new Student() { Name = "John", StudentID = 10 };
List<Student> stu = new List<Student>();
foreach (Student studnt in s)
{
stu.Add(studnt);
}
IEnumerable data = stu;
return data;
}
}

8. In the controller, create a method to add new records to the grid as shown in the
following code. In this example, the repository method Add() is being created to
insert records in the database. Refer to the repository action method given below.

Controller

© 2014 Syncfusion. All rights reserved. 80 | Page


Essential Grid for ASP.NET MVC Classic

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used for inserting records into
the data source.
OrderRepository.Add(ord);
//After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes from Editing>OrderRepository Class.

9. In the controller, create a method to save changes as shown in the following code
sample. In this example, the repository method Update() is used to update records to
the data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh


the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

10. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.

Controller

/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{

© 2014 Syncfusion. All rights reserved. 81 | Page


Essential Grid for ASP.NET MVC Classic

// Repository action Delete() deletes the given primary


value record from the data source.
OrderRepository.Delete(OrderID);

// After deleting refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

11. Run the application. The grid will appear as shown below.

Figure 26: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

12. Edit any row. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 82 | Page


Essential Grid for ASP.NET MVC Classic

Figure 27: Data binding support for CustomerID column in the grid

4.2.5.3.1.2.2 Through GridPropertiesModel


The steps to configure the data binding support for drop-down column features using the
GridPropertiesModel are:

1. Create a model in the application. Refer to How to>Adding a Model to the


Application and Editing>EditableOrder Class.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource(System.Collections.IEnumerable)ViewData["DropDownSo
urce"], "Name", "StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>

View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource(System.Collections.IEnumerable)ViewData["DropDownSo
urce"], "Name", "StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
)

4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.

© 2014 Syncfusion. All rights reserved. 83 | Page


Essential Grid for ASP.NET MVC Classic

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};
ViewData["DropDownSource"] = DropDown;
ViewData["GridModel"] = model; // Pass the model from the
controller to the view using ViewData

5. In the controller, pass the IEnumerable data to the dropdown ViewData.

Controller

public IEnumerable DropDown


{
get
{
Student[] s = new Student[10];
s[0] = new Student() { Name = "Nancy", StudentID = 1 };
s[1] = new Student() { Name = "Andrew", StudentID = 2 };
s[2] = new Student() { Name = "Janet", StudentID = 3 };
s[3] = new Student() { Name = "Margaret", StudentID = 4 };
s[4] = new Student() { Name = "Steven", StudentID = 5 };
s[5] = new Student() { Name = "Michael", StudentID = 6 };
s[6] = new Student() { Name = "Robert", StudentID = 7 };
s[7] = new Student() { Name = "Laura", StudentID = 8 };
s[8] = new Student() { Name = "Anne", StudentID = 9 };
s[9] = new Student() { Name = "John", StudentID = 10 };
List<Student> stu = new List<Student>();
foreach (Student studnt in s)
{
stu.Add(studnt);
}
IEnumerable data = stu;
return data;
}
}

6. Enable editing using the Editing property in the GridPropertiesModel and


configure the editing properties, such as AllowNew, AllowEdit, and AllowDelete.
7. Specify the grid editing mode using the EditMode property.
8. Specify the Primary property which uniquely identifies the grid record.

© 2014 Syncfusion. All rights reserved. 84 | Page


Essential Grid for ASP.NET MVC Classic

9. Add the edit setting to the model.


10. Essential Grid allows for adding new records using grid toolbar items. Refer to
Concepts and Features>Editing.
11. In the controller, create a method to add new records to the grid as shown below. In
this example, the repository method Add() is being created to insert records in the
database. Refer to the repository action method given in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used for inserting records
into the data source.
OrderRepository.Add(ord);

//After adding the record into the database, refresh the


grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes in Editing>OrderRepository Class.

12. In the controller, create a method to save changes, as shown in the following code.
In this example, the repository method Update() is used to update records in the
data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh


the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

© 2014 Syncfusion. All rights reserved. 85 | Page


Essential Grid for ASP.NET MVC Classic

13. In the controller, create a method to delete the records from the database as
displayed below.

In this example, the repository action Delete() will delete the record from the data source.

Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

14. Run the application. The grid will appear as shown in the following screenshot.

Figure 28: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

15. Edit any row. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 86 | Page


Essential Grid for ASP.NET MVC Classic

Figure 29: Data binding support for CustomerID column in the grid

4.2.5.3.2 Bind drop-down data using Action Mapper


There are two overload methods available under the action mapper type. The following two
overload methods are not supported by server mode.
1. Action mapper
2. Action mapper with text and value field

4.2.5.3.2.1 Action mapper

The DropDownDataSource can be configured in two ways:

1. Through GridBuilder
2. Through GridPropertiesModel

4.2.5.3.2.1.1 Through GridBuilder


The steps to configure the data binding support for drop-down column features using
GridBuilder are:

1. Create a model in the application. Refer to How to>Adding a Model to the Application
and Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete.
5. Essenital Grid allows adding new records through grid toolbar items. Refer to
Concepts and Features>Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and
Features>Editing.

© 2014 Syncfusion. All rights reserved. 87 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource((IEnumerable<DataSource.Models.EditableOrder>)ViewDa
ta["data"])
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource((IEnumerable<DataSource.Models.EditableOrder>)ViewDa
ta["data"])
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}

7. Render the view.

© 2014 Syncfusion. All rights reserved. 88 | Page


Essential Grid for ASP.NET MVC Classic

Controller
public ActionResult Index()
{
ViewData["data"] = OrderRepository.GetAllRecords();
return View();
}

8. In order to work with editing actions, create a Post method for the Index actions
and bind the data source to the grid as shown in the following code.

Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

9. In the controller, create the method for the action name that has been specified in the
view to get the details of the drop-down list for that column.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getDropDownDetails()
{
var s = DropDown;
return Json(s, JsonRequestBehavior.AllowGet);
}

public IEnumerable DropDown


{
get
{
// .DropDownDataSource(IEnumerable datasource)
IEnumerable data = new
NorthwindDataContext().Employees.Select(emp=>emp.FirstName);
return data;
}
}

10. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to
the repository action method shown below.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)

© 2014 Syncfusion. All rights reserved. 89 | Page


Essential Grid for ASP.NET MVC Classic

{
//Repository action method Add is used to insert records into data
source.
OrderRepository.Add(ord);
//After adding the record into database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes from Editing>OrderRepository Class.

11. In the controller, create a method to save changes. In this example, the repository
method Update() is used to update records to the data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh


the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

12. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.

Controller

/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);

// After deleting refresh the grid.

© 2014 Syncfusion. All rights reserved. 90 | Page


Essential Grid for ASP.NET MVC Classic

var data = OrderRepository.GetAllRecords();


return data.GridActions<EditableOrder>();
}

13. Run the application. The grid will appear as shown below.

Figure 30: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

14. Edit any row. The grid will appear as shown below.

Figure 31: Data binding support for CustomerID column in the grid

4.2.5.3.2.1.2 Through GridPropertiesModel

© 2014 Syncfusion. All rights reserved. 91 | Page


Essential Grid for ASP.NET MVC Classic

The steps to configure the data binding support for drop-down column features using the
GridPropertiesModel are:

1. Create a model in the application. Refer to How to>Adding a Model to the


Application and Editing>EditableOrder Class.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>

4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),

© 2014 Syncfusion. All rights reserved. 92 | Page


Essential Grid for ASP.NET MVC Classic

ActionMode = ActionMode.JSON,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.

5. In order to work with editing actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

6. In the controller, create the method for the action name that has been specified in
the view to get the details of the drop-down list.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getDropDownDetails()
{
var s = DropDown;
return Json(s, JsonRequestBehavior.AllowGet);
}

public IEnumerable DropDown


{
get
{
// .DropDownDataSource(IEnumerable datasource)
IEnumerable data = new
NorthwindDataContext().Employees.Select(emp=>emp.FirstName);
return data;
}
}

7. Enable editing by using the Editing property in the GridPropertiesModel and


configure the editing properties such as AllowNew, AllowEdit, and AllowDelete.
8. Specify the grid editing mode using the EditMode property.
9. Specify the Primary property which uniquely identifies the grid record.

© 2014 Syncfusion. All rights reserved. 93 | Page


Essential Grid for ASP.NET MVC Classic

10. Add the edit setting to the model.


11. Essential Grid allows adding new records using grid toolbar items. Refer to
Concepts and Features>Editing.
12. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to
the repository action method given in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//The repository action method Add is used to insert records
into the data source.
OrderRepository.Add(ord);

//After adding the record into the database, refresh the


grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes in Editing>OrderRepository Class.

13. In the controller, create a method to save changes, as shown in the following code.
In this example, the repository method Update() is used to update records in the
data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh


the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

14. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller

© 2014 Syncfusion. All rights reserved. 94 | Page


Essential Grid for ASP.NET MVC Classic

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

15. Run the application. The grid will appear as shown in the following screenshot:

Figure 32: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

16. Edit any row. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 95 | Page


Essential Grid for ASP.NET MVC Classic

Figure 33: Data binding support for CustomerID column in the grid

4.2.5.3.2.2 Action Mapper with text and value field

DropDownDataSource can be configured in two ways:

1. Through GridBuilder
2. Through GridPropertiesModel

4.2.5.3.2.2.1 Through GridBuilder


The steps to configure data binding support for drop-down column features using GridBuilder
are:

1. Create a model in the application. Refer to How to>Adding a Model to the Application
and Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing by using the Editing method and configure the editing properties such
as AllowNew, AllowEdit, and AllowDelete.
5. Essenital Grid allows adding new records through grid toolbar items. Refer to
Concepts and Features>Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and
Features>Editing.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource((IEnumerable<DataSource.Models.EditableOrder>)ViewDa
ta["data"])
.Caption("Orders")

© 2014 Syncfusion. All rights reserved. 96 | Page


Essential Grid for ASP.NET MVC Classic

.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails","Name","StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource((IEnumerable<DataSource.Models.EditableOrder>)ViewDa
ta["data"])
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails","Name","StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}

7. Render the view.

Controller
public ActionResult Index()
{
ViewData["data"] = OrderRepository.GetAllRecords();
return View();
}

© 2014 Syncfusion. All rights reserved. 97 | Page


Essential Grid for ASP.NET MVC Classic

8. In order to work with editing actions, create a Post method for Index actions and bind
the data source to the grid as shown in the following code.

Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

9. In the controller, create the method for the action name that has been specified in the
view to get the details of the drop-down list.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getDropDownDetails()
{
var s = DropDown;
return Json(s, JsonRequestBehavior.AllowGet);
}

public IEnumerable DropDown


{
get
{
Student[] s = new Student[10];
s[0] = new Student() { Name = "Nancy", StudentID = 1 };
s[1] = new Student() { Name = "Andrew", StudentID = 2 };
s[2] = new Student() { Name = "Janet", StudentID = 3 };
s[3] = new Student() { Name = "Margaret", StudentID = 4 };
s[4] = new Student() { Name = "Steven", StudentID = 5 };
s[5] = new Student() { Name = "Michael", StudentID = 6 };
s[6] = new Student() { Name = "Robert", StudentID = 7 };
s[7] = new Student() { Name = "Laura", StudentID = 8 };
s[8] = new Student() { Name = "Anne", StudentID = 9 };
s[9] = new Student() { Name = "John", StudentID = 10 };
List<Student> stu = new List<Student>();
foreach (Student studnt in s)
{
stu.Add(studnt);
}
IEnumerable data = stu;
return data;
}
}

10. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to
the repository action method given below.

© 2014 Syncfusion. All rights reserved. 98 | Page


Essential Grid for ASP.NET MVC Classic

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used to insert records into the
data source.
OrderRepository.Add(ord);
//After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes from Editing>OrderRepository Class.

11. In the controller, create a method to save changes. In this example, the repository
method Update() is used to update records to the data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh


the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

12. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.

Controller

/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary

© 2014 Syncfusion. All rights reserved. 99 | Page


Essential Grid for ASP.NET MVC Classic

value record from the data source.


OrderRepository.Delete(OrderID);

// After deleting refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

13. Run the application. The grid will appear as shown below.

Figure 34: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

14. Edit any row. The grid will appear as shown below.

Figure 35: Data binding support for CustomerID column in the grid

© 2014 Syncfusion. All rights reserved. 100 | Page


Essential Grid for ASP.NET MVC Classic

4.2.5.3.2.2.2 Through GridPropertiesModel


The steps to configure the data binding support for drop-down column features using
GridPropertiesModel are:

1. Create a model in the application. Refer to How to>Adding a Model to the


Application and Editing>EditableOrder Class.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails","Name","StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>

View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource("getDropDownDetails","Name","StudentID");
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
)

4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.

Controller

© 2014 Syncfusion. All rights reserved. 101 | Page


Essential Grid for ASP.NET MVC Classic

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
ActionMode = ActionMode.JSON,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData

5. In order to work with editing actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.

Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

6. In the controller, create the method for the action name that has been specified in
the view to get the details of the drop-down list.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult getDropDownDetails()
{
var s = DropDown;
return Json(s, JsonRequestBehavior.AllowGet);
}

public IEnumerable DropDown


{
get
{
Student[] s = new Student[10];
s[0] = new Student() { Name = "Nancy", StudentID = 1 };
s[1] = new Student() { Name = "Andrew", StudentID = 2 };
s[2] = new Student() { Name = "Janet", StudentID = 3 };
s[3] = new Student() { Name = "Margaret", StudentID = 4 };
s[4] = new Student() { Name = "Steven", StudentID = 5 };
s[5] = new Student() { Name = "Michael", StudentID = 6 };
s[6] = new Student() { Name = "Robert", StudentID = 7 };
s[7] = new Student() { Name = "Laura", StudentID = 8 };

© 2014 Syncfusion. All rights reserved. 102 | Page


Essential Grid for ASP.NET MVC Classic

s[8] = new Student() { Name = "Anne", StudentID = 9 };


s[9] = new Student() { Name = "John", StudentID = 10 };
List<Student> stu = new List<Student>();
foreach (Student studnt in s)
{
stu.Add(studnt);
}
IEnumerable data = stu;
return data;
}
}

7. Enable editing by using the Editing property in the GridPropertiesModel and


configure the editing properties such as AllowNew, AllowEdit, and AllowDelete.
8. Specify the grid editing mode using the EditMode property.
9. Specify the Primary property which uniquely identifies the grid record.
10. Add the edit setting to the model.
11. Essential Grid allows adding new records using grid toolbar items. Refer to
Concepts and Features>Editing.
12. In the controller, create a method to add new records to the grid as given below. In
this example, the repository method Add() is being created to insert records in the
database. Refer to the repository action method given in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used to insert records into
the data source.
OrderRepository.Add(ord);

//After adding the record into the database, refresh the


grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes in Editing>OrderRepository Class.

13. In the controller, create a method to save changes, as shown in the following code.
In this example, the repository method Update() is used to update records in the
data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{

© 2014 Syncfusion. All rights reserved. 103 | Page


Essential Grid for ASP.NET MVC Classic

//Repository action method Update used to update the


records into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh


the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

14. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

15. Run the application. The grid will appear as shown in the following screenshot.

© 2014 Syncfusion. All rights reserved. 104 | Page


Essential Grid for ASP.NET MVC Classic

Figure 36: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

16. Edit any row. The grid will appear as shown below.

Figure 37: Data binding support for CustomerID column in the grid

4.2.5.3.3 Bind drop-down data using Array


This overload method is supported by both server and JSON mode.

The DropDownDataSource can be configured in two ways:

1. Through GridBuilder
2. Through GridPropertiesModel

© 2014 Syncfusion. All rights reserved. 105 | Page


Essential Grid for ASP.NET MVC Classic

4.2.5.3.3.1 Through GridBuilder


The steps to configure the data binding support for drop-down column features using
GridBuilder are:

1. Create a model in the application. Refer to How to>Adding a Model to the Application
and Editing>EditableOrder Class.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Enable editing by using the Editing method and configure the editing properties such
as AllowNew, AllowEdit, and AllowDelete.
5. Essenital Grid allows adding new records through grid toolbar items. Refer to
Concepts and Features>Editing.
6. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and
Features>Editing.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((Array)ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")

.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")

© 2014 Syncfusion. All rights reserved. 106 | Page


Essential Grid for ASP.NET MVC Classic

.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((Array)ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}

7. In the controller, pass the IEnumerable data to the ViewData.

Controller

public ActionResult Index()


{
ViewData["DropDownSource"] = DropDown;
var data = OrderRepository.GetAllRecords();
return View(data);
}

public Array DropDown


{
get
{
string[] strArray = new string[] { "Mahesh Chand", "Mike Gold",
"Raj Beniwal", "Praveen Kumar", "Dinesh Beniwal" };
return strArray;
}
}

8. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to
the repository action method given below.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used to insert records into the
data source.
OrderRepository.Add(ord);
//After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

© 2014 Syncfusion. All rights reserved. 107 | Page


Essential Grid for ASP.NET MVC Classic

Note: Refer to the repository action codes from Editing>OrderRepository Class.

9. In the controller, create a method to save changes. In this example, the repository
method Update() is used to update records to the data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update used for perform update
the records into datasource
OrderRepository.Update(ord);

//After save the records into datasource refresh the Grid


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

10. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.

Controller

/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);

// After deleting refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

11. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 108 | Page


Essential Grid for ASP.NET MVC Classic

Figure 38: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

12. Edit any row. The grid will appear as shown below.

Figure 39: Data binding support for CustomerID column in the grid

4.2.5.3.3.2 Through GridPropertiesModel


The steps to configure the data binding support for drop-down column features using the
GridPropertiesModel are:

1. Create a model in the application. Refer to How to>Adding a Model to the


Application and Editing>EditableOrder Class.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

© 2014 Syncfusion. All rights reserved. 109 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((Array)ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
%>

View [cshtml]
@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID")
.CellEditType(CellEditType.DropdownEdit)
.DropDownDataSource((Array)ViewData["DropDownSource"]);
column.Add(p => p.Verified).HeaderText("Verified");
column.Add(p => p.ShipRegion).HeaderText("Ship Region");
column.Add(p => p.Freight).HeaderText("Freight");
})
)

4. Create a GridPropertiesModel in the Index action and assign the grid properties in
the model.

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};
ViewData["DropDownSource"] = DropDown;

© 2014 Syncfusion. All rights reserved. 110 | Page


Essential Grid for ASP.NET MVC Classic

ViewData["GridModel"] = model; // Pass the model from


controller to view using ViewData

5. In the controller, pass the IEnumerable data to the dropdown ViewData.

Controller

public Array DropDown


{
get
{
string[] strArray = new string[] { "Mahesh Chand", "Mike Gold",
"Raj Beniwal", "Praveen Kumar", "Dinesh Beniwal" };
return strArray;
}
}

6. Enable editing by using the Editing property in the GridPropertiesModel and


configure the editing properties such as AllowNew, AllowEdit, and AllowDelete.
7. Specify the grid editing mode using the EditMode property.
8. Specify the Primary property which uniquely identifies the grid record.
9. Add the edit setting to the model.
10. Essential Grid allows adding new records using grid toolbar items. Refer to
Concepts and Features>Editing.
11. In the controller, create a method to add new records to the grid. In this example, the
repository method Add() is being created to insert records in the database. Refer to
the repository action method given in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add is used insert records into the
data source.
OrderRepository.Add(ord);

//After adding the record into database, refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes in Editing>OrderRepository Class.

12. In the controller, create a method to save changes. In this example, the repository
method Update() is used to update records in the data source.

© 2014 Syncfusion. All rights reserved. 111 | Page


Essential Grid for ASP.NET MVC Classic

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the data source.
OrderRepository.Update(ord);

//After saving the records into the data source, refresh


the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

13. In the controller, create a method to delete the records from the database as
displayed below. In this example, the repository action Delete() will delete the record
from the data source.
Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

14. Run the application. The grid will appear as shown in the following screenshot.

© 2014 Syncfusion. All rights reserved. 112 | Page


Essential Grid for ASP.NET MVC Classic

Figure 40: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

15. Edit any row. The grid will appear as shown below

Figure 41: Data binding support for CustomerID column in the grid
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Server Mode/JSON Mode

© 2014 Syncfusion. All rights reserved. 113 | Page


Essential Grid for ASP.NET MVC Classic

4.2.6 Auto-Generated Columns


If no columns are defined, the grid extracts the column from the underlying model and populates
the grid automatically. Every public property that is of primitive .NET type will be added as a
column.

4.2.6.1 Through GridBuilder


1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() in order to bind the data source
alone. Don’t specify any visible column collections to grid. The grid automatically populates
the columns from its model.
View [ASPX]

<%=Html.Syncfusion().Grid<Product>("ProductGrid")
.Datasource(Model)
.Caption("Product Details")
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Product>("ProductGrid")
.Datasource(Model)
.Caption("Product Details")
}
4. Set its data source and render the view.
Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Products.Take(15);
return View(data);
}

5. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 114 | Page


Essential Grid for ASP.NET MVC Classic

Figure 42: Grid with Auto-Generated Columns

4.2.6.2 Through GridPropertiesModel

1. Create a model in the application (refer to How to>Adding a Model to the Application)
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource in order to bind the data source
alone. Don’t specify any visible column collections to the grid. The grid automatically
populates the columns from its model.
View [ASPX]

<%=Html.Syncfusion().Grid<Product>("ProductGrid",(GridPropertiesModel)V
iewData["GridModel"]) %>

View [cshtml]
@(
Html.Syncfusion().Grid<Product>("ProductGrid",(GridPropertiesModel)View
Data["GridModel"]))

4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from controller to view using the ViewData class as given below.
Controller

/// <summary>
/// Used for display the grid.
/// </summary>
/// <returns> View page which displays the grid.</returns>
public ActionResult Index()

© 2014 Syncfusion. All rights reserved. 115 | Page


Essential Grid for ASP.NET MVC Classic

{
GridPropertiesModel<Product> model = new
GridPropertiesModel<Product>()
{
DataSource = new
NorthwindDataContext().Products.Take(15),
Caption = "Product Grid"
};
ViewData["GridModel"]=model;
return View();
}

5. Run the application. The grid will appear as shown below.

Figure 43: Grid with Auto-Generated Columns

4.2.7 Custom Binding


Essential Grid processes the data source by using the built-in LINQ expressions to perform
paging, sorting, grouping, filtering, and editing actions. However, in some cases you may want to
bypass the built-in data source processing and process the data manually. This is called “custom
binding.”
Essential Grid supports custom binding to perform paging, sorting, and filtering actions.

Properties

Property Description Type of Value it Any other


property accepts dependencies/sub-
properties
associated
EnableOnDemand Gets or sets a value Boolean True/false NA
indicating whether
OnDemand is
enabled.

TotalRecordCount Gets or sets the Long 0 to

© 2014 Syncfusion. All rights reserved. 116 | Page


Essential Grid for ASP.NET MVC Classic

total record count. long.MaxValue

Methods

Method Description Parameters Return type


EnableOnDemand() Used to enable the custom --- IGridBuilder<T>
binding mode to True.

TotalRecordCount() Used to set the total record Long 0 to


count. long.MaxValue

Where(List<FilterConditions> IQueryable extension method List of Filter conditions


filters) is used to filter the record FilterConditions collections
from the given data source.

GridActions<T>(Long GridActionResult method is Total record Action result


totalrecordcount) used to call the custom count
binding grid post actions.

You can work with the custom binding feature through two ways:
 GridBuilder
 GridPropertiesModel

4.2.7.1 Through GridBuilder

The steps to work with the custom binding feature through GridBuilder are as follows:
1. Create a model in the application. Refer to How to>Adding Model to the Application.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource() to bind the data source. In this
example, sorting, paging, and filtering are enabled.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dd/MM/yyyy}");

© 2014 Syncfusion. All rights reserved. 117 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(c => c.CustomerID).HeaderText("Customer ID");


column.Add(c => c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship City");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.EnableFiltering()
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dd/MM/yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship City");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.EnableFiltering().Render();
}

4. Enable the custom binding mode by using the EnableOnDemand() method.


View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
……………
……………
.EnableOnDemand()
……………
……………
%>

© 2014 Syncfusion. All rights reserved. 118 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
……………
……………
.EnableOnDemand()
……………
……………
.Render();
}

5. Set the TotalRecordCount by specifying the total record count the grid should display. This
field is required to display the grid pager accurately.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
……………
……………
.TotalRecordCount(200)
……………
……………
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
……………
……………
.TotalRecordCount(200)
……………
……………
.Render();
}
6. In the grid Post actions, check the request type. If the action type is paging, sorting, or
filtering the request, then process the data and bind the data to the action result. Bind the
GridActionResult with the totalrecount which is used to render the pages in all the
custom binding actions.
Controller

/// <summary>

© 2014 Syncfusion. All rights reserved. 119 | Page


Essential Grid for ASP.NET MVC Classic

/// Grid actions for paging/sorting/grouping/filtering/editing.


/// OnDemand mode enabled only for paging, sorting, and filtering
actions.
/// New FilterConditions property added in PagingParams which holds the
filter
/// conditions.
/// </summary>
/// <param name="args">Paging params.</param>
/// <returns>Action result.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = null;
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
if (args.EnableOnDemand && (currentRequest ==
RequestType.Sorting || currentRequest == RequestType.Paging ||
currentRequest == RequestType.Filtering))
{
data = this.GetData(args);
}
else
{
data = new
NorthwindDataContext().Orders.Take(200).ToList();
}
return data.GridActions<Order>(totalrecordCount);
}

/// <summary>
/// Utility method for performing data processing.
/// </summary>
/// <param name="args">Paging params.</param>
/// <returns>IQueryable data source.</returns>
private IEnumerable GetData(PagingParams args)
{
int pagesize = args.PageSize == 0 ? 12 :
Convert.ToInt32(args.PageSize);
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();

IQueryable ds = data.AsQueryable();

// If filter conditions exist filter the data source using


filtering
// extensions, which use the expression-based query
generator used for applying filters.
if (args.FilterDescriptors != null &&
args.FilterDescriptors.Count() > 0)
ds = ds.Where(args.FilterDescriptors);

© 2014 Syncfusion. All rights reserved. 120 | Page


Essential Grid for ASP.NET MVC Classic

// SortColumn and SortDirections properties are removed


from PagingParams.
// New SortDescriptors property added in PagingParams. It
contains a list of Sort column values and their directions.
if (args.SortDescriptors != null)
{
for (int i = 0; i < args.SortDescriptors.Count; i++)
{
var sortColumnName =
args.SortDescriptors[i].ColumnName;
if (i == 0)
{

if (args.SortDescriptors[i].SortDirection ==
ListSortDirection.Ascending)
{
ds = ds.OrderBy(sortColumnName);

}
else if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Descending)
{
ds = ds.OrderByDescending(sortColumnName);
}
}
else
{
if (args.SortDescriptors[i].SortDirection ==
ListSortDirection.Ascending)
{
ds = ds.ThenBy(sortColumnName);
}
else if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Descending)
{
ds = ds.ThenByDescending(sortColumnName);
}
}
}
}
totalrecordCount = ds.Count();
if (totalrecordCount > 0)
data =
ds.Skip(Convert.ToInt32(args.StartIndex)).Take(pagesize);
else
data = ds;

return data;
}
7. Run the application. The grid will appear as displayed below.

© 2014 Syncfusion. All rights reserved. 121 | Page


Essential Grid for ASP.NET MVC Classic

Figure 44: Grid with the Custom Binding Enabled Mode

4.2.7.2 Through GridPropertiesModel

The steps to work with the custom binding feature through GridPropertiesModel are as follows:
1. Create a model in the application. (Refer to How to>Adding a Model to the Application.)
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel",
column=> {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel",

© 2014 Syncfusion. All rights reserved. 122 | Page


Essential Grid for ASP.NET MVC Classic

column=> {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
}))

4. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model. In this example, sorting, paging, and filtering are enabled.
Controller

GridPropertiesModel<Order> model = new GridPropertiesModel<Order>()


{
DataSource = new
NorthwindDataContext().Orders.Take(200),
Caption = "Product",
AllowPaging = true,
AllowSorting = true,
AllowFiltering=true

};

5. Enable the custom binding mode by using the EnableOnDemand property.


Controller

GridPropertiesModel<Order> model = new GridPropertiesModel<Order>()


{
DataSource = this.GetData(new PagingParams()),
Caption = "Product",
AllowPaging = true,
AllowSorting = true,
AllowFiltering=true,

© 2014 Syncfusion. All rights reserved. 123 | Page


Essential Grid for ASP.NET MVC Classic

EnableOnDemand=true,

};

6. Set the TotalRecordCount by specifying the total record count the grid should display. This
field is required to display the grid pager accurately.
Controller

GridPropertiesModel<Order> model = new GridPropertiesModel<Order>()


{
DataSource = this.GetData(new PagingParams()),
Caption = "Product",
……………
……………
EnableOnDemand=true,
TotalRecordsCount=200
};

7. In the grid Post actions, check the request type. If the action type is paging, sorting, or
filtering a request, then process the data and bind the data to the action result. Bind the
GridActionResult with the totalrecount which is used to render the pages in all the
custom binding actions.
/// <summary>
/// Grid actions for paging/sorting/grouping/filering/editing.
/// OnDemand mode enabled only for paging, sorting, and
filtering actions.
/// New FilterConditions property added in paging params which
holds the filter
/// conditions.
/// </summary>
/// <param name="args">Paging params.</param>
/// <returns>Action result.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = null;
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
if (args.EnableOnDemand && (currentRequest ==
RequestType.Sorting || currentRequest == RequestType.Paging ||
currentRequest == RequestType.Filtering))
{
data = this.GetData(args);
}
else
{

© 2014 Syncfusion. All rights reserved. 124 | Page


Essential Grid for ASP.NET MVC Classic

data = new
NorthwindDataContext().Orders.Take(200).ToList();
}
return data.GridActions<Order>(totalrecordCount);
}

/// <summary>
/// Utility method for perform the data processing.
/// </summary>
/// <param name="args">Paging params.</param>
/// <returns>IQueryable data source.</returns>
private IEnumerable GetData(PagingParams args)
{
int pagesize = args.PageSize == 0 ? 12 :
Convert.ToInt32(args.PageSize);
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();

IQueryable ds = data.AsQueryable();

// If filter conditions exist filter the data source using


filtering
// extensions, which use the expression-based query
generator for applying filters.
if (args.FilterDescriptors != null &&
args.FilterDescriptors.Count() > 0)
ds = ds.Where(args.FilterDescriptors);

//SortColumn and SortDirections properties are removed from


PagingParams.
//New SortDescriptors property added in PagingParams. It
contains list of SortColumn values and their directions.
if (args.SortDescriptors != null)
{
for (int i = 0; i < args.SortDescriptors.Count; i++)
{
var sortColumnName =
args.SortDescriptors[i].ColumnName;
if (i == 0)
{

if (args.SortDescriptors[i].SortDirection ==
ListSortDirection.Ascending)
{
ds = ds.OrderBy(sortColumnName);

}
else if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Descending)
{

© 2014 Syncfusion. All rights reserved. 125 | Page


Essential Grid for ASP.NET MVC Classic

ds = ds.OrderByDescending(sortColumnName);
}
}
else
{
if (args.SortDescriptors[i].SortDirection ==
ListSortDirection.Ascending)
{
ds = ds.ThenBy(sortColumnName);
}
else if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Descending)
{
ds = ds.ThenByDescending(sortColumnName);
}
}
}
}
totalrecordCount = ds.Count();
if (totalrecordCount > 0)
data =
ds.Skip(Convert.ToInt32(args.StartIndex)).Take(pagesize);
else
data = ds;

return data;
}

8. Run the application. The grid will appear as displayed below.

Figure 45: Grid with the Custom Binding Enabled Mode


Sample Link
To view the samples, follow the steps below:

© 2014 Syncfusion. All rights reserved. 126 | Page


Essential Grid for ASP.NET MVC Classic

1. Open the Grid sample browser from the dashboard (refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > Custom Data Binding

4.2.8 Web Service Data Binding


Web service data binding is one of the best features in ASP.NET MVC with rich declarative data
binding. This feature allows you to bind the grid to Web services using object data sources. An
important advantage of Web services is that they are "cross platform and cross language.”
A grid bound using Web services also enables rich capabilities over data like sorting, paging,
filtering, updating, deleting, and inserting—that data-bound UI controls can use automatically.
The main advantages of Web services are platform independence and reusability.

Use Case Scenarios


Multiple users can access the same data source without changing the underlying platform.

Binding the Grid to Web Services in an Application

4.2.8.1 Through GridBuilder


1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the URL for Web service data binding using the WebService() method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")

.Caption("Orders")

.WebService("/Models/Orders.asmx/RenderOrders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("OrderID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
})

.EnablePaging().PageSettings(p =>
p.PageCount(5))
.EnableSorting()
.EnableGrouping().EnableFiltering()
.AutoFormat(Skins.Sandune)
.ToolBar(tools =>

© 2014 Syncfusion. All rights reserved. 127 | Page


Essential Grid for ASP.NET MVC Classic

{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Editing( edit=>{
edit.AllowEdit(true,
"/Models/Orders.asmx/OrderSave")
.AllowNew(true,
"/Models/Orders.asmx/AddOrder")
.AllowDelete(true,
"/Models/Orders.asmx/DeleteOrder")
.EditMode(GridEditMode.InlineForm)
.PrimaryKey(key => key.Add(p => p.OrderID));
})

%>

View [cshtml]
@{Html.Syncfusion().Grid<Order>("Grid1")

.Caption("Orders")

.WebService("/Models/Orders.asmx/RenderOrders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("OrderID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
})

.EnablePaging().PageSettings(p =>
p.PageCount(5))
.EnableSorting()
.EnableGrouping().EnableFiltering()
.AutoFormat(Skins.Sandune)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})

© 2014 Syncfusion. All rights reserved. 128 | Page


Essential Grid for ASP.NET MVC Classic

.Editing( edit=>{
edit.AllowEdit(true,
"/Models/Orders.asmx/OrderSave")
.AllowNew(true,
"/Models/Orders.asmx/AddOrder")
.AllowDelete(true,
"/Models/Orders.asmx/DeleteOrder")
.EditMode(GridEditMode.InlineForm)
.PrimaryKey(key => key.Add(p => p.OrderID));
})

.Render();
}

5. Render the view.


Controller
public ActionResult Index()
{
return View();
}

6. Bind the grid to Web services using object data sources. The Web service method must
have a parameter webParams of type WebServiceParams which maintains the current
state of the grid for filtering, editing, sorting, paging, and grouping actions. Also, the Web
service method should return the GridWebService object.

[WebMethod] // The parameter name should be exactly "webParams"


public GridWebService RenderOrders(WebServiceParams webParams)
{
IEnumerable data = new
NorthwindDataContext().OrderDetails.Take(100).ToList();
return data.GridWebServiceAction<OrderDetail>(webParams);
}

8.

Note: The parameter name must be exactly “webParams”.


7. Create a WebMethod for updating the records in the editing feature. The Web service
method must have parameters webParams of type WebServiceParams and
datasourceObj of the particular data source object type. The datasourceObj parameter
contains the updated record information.
9.

// The parameter names should be exactly "webParams" and “datasourceObj”

© 2014 Syncfusion. All rights reserved. 129 | Page


Essential Grid for ASP.NET MVC Classic

[WebMethod]
public GridWebService OrderSave(WebServiceParams webParams, Order
datasourceObj)
{

Order result = context.Orders.Single(p => p.OrderID ==


datasourceObj.OrderID);
if (result != null)
{
result.OrderID = datasourceObj.OrderID;
result.EmployeeID = datasourceObj.EmployeeID;
result.CustomerID = datasourceObj.CustomerID;
result.ShipAddress = datasourceObj.ShipAddress;
result.ShipCountry = datasourceObj.ShipCountry;
context.SubmitChanges();
}
IEnumerable data = new
NorthwindDataContext().Orders.Take(100).ToList();
return data.GridWebServiceAction<Order>(webParams);
}

8. Create a WebMethod for adding records. The Web service method must have parameters
webParams of type WebServiceParams and datasourceObj of the particular data source
object type. The datasourceObj parameter contains the new record which has to be
added.

// The parameter names should be exactly "webParams" and


“datasourceObj”
[WebMethod]
public GridWebService AddOrder(WebServiceParams webParams, Order
datasourceObj)
{
context.Orders.InsertOnSubmit(datasourceObj);
context.SubmitChanges();
IEnumerable data = new
NorthwindDataContext().Orders.Take(100).ToList();
return data.GridWebServiceAction<Order>(webParams);
}

9. Create a WebMethod for adding records. The Web service method must have parameters
webParams of type WebServiceParams and KeyValue of the same type as the primary

© 2014 Syncfusion. All rights reserved. 130 | Page


Essential Grid for ASP.NET MVC Classic

column. The KeyValue parameter contains the particular record’s primary column value
which is used to delete that particular record.

// The parameter names should be exactly "webParams" and “KeyValue”


[WebMethod]
public GridWebService DeleteOrder(WebServiceParams webParams, int
KeyValue)
{
Order order = context.Orders.Single(p => p.OrderID == KeyValue);
context.Orders.DeleteOnSubmit(order);
context.SubmitChanges();
IEnumerable data = new
NorthwindDataContext().Orders.Take(100).ToList();
return data.GridWebServiceAction<Order>(webParams);
}

10. Run the application. The grid will appear as shown in the following figure:

Figure 46: Grid—Web Service Data Binding

4.2.8.2 Through GridPropertiesModel

1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", column=>

© 2014 Syncfusion. All rights reserved. 131 | Page


Essential Grid for ASP.NET MVC Classic

{
column.Add(p =>
p.OrderID).HeaderText("OrderID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
}));

%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("Grid1", column=>
{
column.Add(p => p.OrderID).HeaderText("OrderID");
column.Add(p => p.EmployeeID).HeaderText("EmployeeID");
column.Add(p => p.ShipAddress).HeaderText("ShipAddress");
column.Add(p => p.ShipCountry).HeaderText("ShipCountry");
})
)

4. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging=true,
AllowSorting=true,
AllowGrouping=true,
AutoFormat = Skins.Sandune
};
gridModel.WebService = "/Models/Orders.asmx/OrderSave";
gridModel.PageSetting.PageCount = 5;

5. Enable editing by using the Editing property in the GridPropertiesModel, and configure
the editing properties such as AllowNew, AllowEdit, and AllowDelete as shown in the
following code sample:
Controller

© 2014 Syncfusion. All rights reserved. 132 | Page


Essential Grid for ASP.NET MVC Classic

GridEditing edit = new GridEditing() { AllowEdit = true,


AllowDelete = true, AllowNew = true };

// Set the action mappers for insert, delete, and save


actions.
edit.DeleteMapper = "/Models/Orders.asmx/DeleteOrder";
edit.InsertMapper = "/Models/Orders.asmx/AddOrder";
edit.GridSaveMapper = "/Models/Orders.asmx/OrderSave";
edit.EditMode = GridEditMode.Normal;
edit.PrimaryKey = new List<string>() { "OrderID" };
gridModel.Editing = edit;

6. Essential Grid allows adding new records through grid toolbar items. In this example, the
AddNew, Edit, Delete, Save, and Cancel buttons have been added as toolbar items as
shown in the following code sample:
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
// Add the add new, edit, delete, save, and cancel buttons in the
toolbar.
toolbar.Items.Add(new ToolbarOptions() {
ItemType=GridToolBarItems.AddNew});
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Update });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Delete });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Cancel });
gridModel.ToolBar = toolbar;
ViewData["Grid1"] = gridModel;
return View();

7. Bind the grid to a Web service using object data sources. The Web service method must
have a parameter webParams of the type WebServiceParams which maintains the current
state of the grid for filtering, editing, sorting, paging, and grouping actions. Also, the Web
service method should return the GridWebService object.

[WebMethod] // The parameter name should be exactly "webParams"


public GridWebService RenderOrders(WebServiceParams webParams)
{
IEnumerable data = new
NorthwindDataContext().OrderDetails.Take(100).ToList();
return data.GridWebServiceAction<OrderDetail>(webParams);

© 2014 Syncfusion. All rights reserved. 133 | Page


Essential Grid for ASP.NET MVC Classic

Note: The parameter name must be “webParams”.


8. Create a WebMethod for updating records with the editing feature as shown in the
following code samples. The Web service method must have the parameters webParams
of type WebServiceParams and datasourceObj of the particular data source object type.
The datasourceObj parameter contains the updated record information.

// The parameter names should be exactly "webParams" and “datasourceObj”


[WebMethod]
public GridWebService OrderSave(WebServiceParams webParams, Order
datasourceObj)
{

Order result = context.Orders.Single(p => p.OrderID ==


datasourceObj.OrderID);
if (result != null)
{
result.OrderID = datasourceObj.OrderID;
result.EmployeeID = datasourceObj.EmployeeID;
result.CustomerID = datasourceObj.CustomerID;
result.ShipAddress = datasourceObj.ShipAddress;
result.ShipCountry = datasourceObj.ShipCountry;
context.SubmitChanges();
}
IEnumerable data = new
NorthwindDataContext().Orders.Take(100).ToList();
return data.GridWebServiceAction<Order>(webParams);
}

9. Create a WebMethod for adding records. The Web service method must have the
parameters webParams of the type WebServiceParams and datasourceObj of the
particular data source object type. The datasourceObj parameter contains the new record
which has to be added.

// The parameter names should be exactly "webParams" and


“datasourceObj”
[WebMethod]
public GridWebService AddOrder(WebServiceParams webParams, Order
datasourceObj)
{
context.Orders.InsertOnSubmit(datasourceObj);
context.SubmitChanges();
IEnumerable data = new
NorthwindDataContext().Orders.Take(100).ToList();
return data.GridWebServiceAction<Order>(webParams);

© 2014 Syncfusion. All rights reserved. 134 | Page


Essential Grid for ASP.NET MVC Classic

10. Create a WebMethod for adding records as shown in the following code samples. The Web
service method must have the parameters webParams of type WebServiceParams and
KeyValue of the same type as the primary column. The KeyValue parameter contains the
particular record’s primary column value which is used to delete that particular record.

// The parameter names should be exactly "webParams" and “KeyValue”


[WebMethod]
public GridWebService DeleteOrder(WebServiceParams webParams, int
KeyValue)
{
Order order = context.Orders.Single(p => p.OrderID == KeyValue);
context.Orders.DeleteOnSubmit(order);
context.SubmitChanges();
IEnumerable data = new
NorthwindDataContext().Orders.Take(100).ToList();
return data.GridWebServiceAction<Order>(webParams);
}

11. Run the application. The grid will appear as shown in the following figure:

Figure 47: Grid—Web service data binding

Properties

© 2014 Syncfusion. All rights reserved. 135 | Page


Essential Grid for ASP.NET MVC Classic

Any other
Type of dependencies/s
Property Description Value it accepts
property ub-properties
associated
Gets or sets the
URL for binding
the grid to a
WebService string string NA
Web service
using object
data source.

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > Web Service Binding

4.2.9 Dynamic Data Binding

The dynamic data binding feature does not need any parameters to define the grid. This feature
will be useful to dynamically define the ModelType of the grid. According to the data source the
grid will render the columns internally.

Use Case Scenarios

Dynamic data binding can be used for:


1. Automatically generating columns without mapping to column names. (Auto-generated
column support)
2. Dynamically binding data sources to the Grid control. (Dynamic data binding support)

4.2.9.1 Dynamically Bind Data to Grid without mapping to column


names

4.2.9.1.1 Through GridBuilder

To dynamically bind data to the grid through GridBuilder:


1. Create a model in the application (refer to How to>Adding a Model to the Application).

© 2014 Syncfusion. All rights reserved. 136 | Page


Essential Grid for ASP.NET MVC Classic

2. Create a strongly typed view (refer to How to>Strongly Typed View).


3. Create the Grid control in the view of type object and configure its properties.
View [ASPX]

<% =Html.Syncfusion().Grid<object>("Grid1")
.Datasource((IEnumerable)ViewData["data"])
.Caption("Dynamic DataSource")
.AutoFormat(Skins.Almond)
%>

View [cshtml]
@{ Html.Syncfusion().Grid<object>("Grid1")
.Datasource((IEnumerable)ViewData["data"])
.Caption(ViewData["datatype"].ToString())
.AutoFormat(Skins.Almond)
.Render();
}

4. Set its data source in the corresponding ViewData and render the view.
[Controller]
public ActionResult Index()
{

var data = new NorthwindDataContext().Orders;


ViewData["data"] = data;
return View();
}

5. Run the application, the grid will appear as shown below:

© 2014 Syncfusion. All rights reserved. 137 | Page


Essential Grid for ASP.NET MVC Classic

Figure 48: Grid Bound to Dynamic Data Source through GridBuilder

4.2.9.1.2 Through GridPropertiesModel


To dynamically bind data to the grid through GridPropertiesModel:
1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%= Html.Syncfusion().Grid<object>("Grid1",
(GridPropertiesModel<object>)ViewData["GridModel"]
%>

4. Create a GridPropertiesModel of type object in the Index method.


[Controller]
public ActionResult Index()
{
GridPropertiesModel<object> gridModel = new
GridPropertiesModel<object>()
{
DataSource = new NorthwindDataContext().Orders,

© 2014 Syncfusion. All rights reserved. 138 | Page


Essential Grid for ASP.NET MVC Classic

Caption = "Orders",
};

ViewData["GridModel"] = gridModel;
return View();

5. Run the application. The grid will appear as shown below:

Figure 49: Grid Bound to Dynamic Data Source through GridPropertiesModel

4.2.9.2 Dynamically Bind data with mapping the column name as


string

Tables for Methods (Properties and Events Not Applicable)

Methods

Method Description Parameters Type Return type

© 2014 Syncfusion. All rights reserved. 139 | Page


Essential Grid for ASP.NET MVC Classic

UnBound Gets or sets the IsUnBound bool IGridColumnBuilder<T>


column to be
bound or not.

How to Add Columns

4.2.9.2.1 Through GridBuilder


To add columns in a dynamically bound grid through GridBuilder:
1. Create a model in the application (Refer to How to >Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view of type object and configure its properties.
4. Add columns using the following code sample:
View [ASPX]

<% =Html.Syncfusion().Grid<object>("Grid1")
.Datasource((IEnumerable)ViewData["data"])
.Column(col=>{
col.Add("OrderId").UnBound(false);
col.Add("OrderDate").UnBound(false);
col.Add("CustomerID").UnBound(false);
col.Add("ShipDate").UnBound(false);
col.Add("ShipAddress").UnBound(false);
})
.Caption("Dynamic DataSource")
.AutoFormat(Skins.Almond)
%>

View [cshtml]

@{ Html.Syncfusion().Grid<object>("Grid1")
.Datasource((IEnumerable)ViewData["data"])
.Column(col=>{
col.Add("OrderId").UnBound(false);
col.Add("OrderDate").UnBound(false);
col.Add("CustomerID").UnBound(false);
col.Add("ShippedDate").UnBound(false);
col.Add("ShipAddress").UnBound(false);
})
.Caption(ViewData["datatype"].ToString())
.AutoFormat(Skins.Almond)

© 2014 Syncfusion. All rights reserved. 140 | Page


Essential Grid for ASP.NET MVC Classic

.Render();
}

5. Set its data source in corresponding ViewData and render the view.
[Controller]
public ActionResult Index()

var data = new NorthwindDataContext().Orders;


ViewData["data"] = data;

return View();

6. Run the application. The grid will appear as shown below:

© 2014 Syncfusion. All rights reserved. 141 | Page


Essential Grid for ASP.NET MVC Classic

Figure 50: Grid with Columns Added through GridBuilder

4.2.9.2.2 Through GridPropertiesModel


To add columns in a dynamically bound grid through GridPropertiesModel:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
4. Add columns using the code shown below.
View [ASPX]
<%= Html.Syncfusion().Grid<object>("Grid1","GridModel", col => {

col.Add("OrderId").UnBound(false);
col.Add("OrderDate").UnBound(false);
col.Add("CustomerID").UnBound(false);
col.Add("ShippedDate").UnBound(false);
col.Add("ShipAddress").UnBound(false);

} ) %>

View [cshtml]
@( Html.Syncfusion().Grid<object>("Grid1","GridModel", col => {

col.Add("OrderId").UnBound(false);
col.Add("OrderDate").UnBound(false);
col.Add("CustomerID").UnBound(false);
col.Add("ShippedDate").UnBound(false);
col.Add("ShipAddress").UnBound(false);

} ))

5. Create a GridPropertiesModel of type object in the Index method.

[Controller]
public ActionResult Index()
{
GridPropertiesModel<object> gridModel = new
GridPropertiesModel<object>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
};

© 2014 Syncfusion. All rights reserved. 142 | Page


Essential Grid for ASP.NET MVC Classic

ViewData["GridModel"] = gridModel;
return View();

6. Run the application. The Grid will appear as shown below:

Figure 51: Grid with Columns Added through GridPropertiesModel

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > Dynamic Data Binding Mode

4.2.10 DataTable Support


DataTables operate on the principle of progressive enhancement, whereby an enhanced and
interactive table will be presented to the end user if their browser has the required capabilities. In
combination with the default values for the features in DataTables, this makes it very easy to
integrate directly into your Web site or Web application. Optionally, you can load data based on
both server mode and JSON mode.

© 2014 Syncfusion. All rights reserved. 143 | Page


Essential Grid for ASP.NET MVC Classic

Properties
Property Description Type of Value it Accepts Any Other
Property Dependencies/Sub-
Properties
Associated
DataSource Gets or sets the DataTable Any DataTable None
data source for the data.
Grid control.

Methods
Method Description Parameters Return Type

Datasource Used to set a data source to the DataTable data source IGridBuilder<T>
(DataTable) Grid control.

4.2.10.1 Through GridBuilder


1. Create a model in the application (Refer to How to > Adding a Model to the Application).

2. Create a strongly typed view (Refer to How to>Strongly Typed View).


3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]
<%=Html.Syncfusion().Grid<System.Data.DataRow>("OrdersGrid")
.Datasource(Model)
.Column(col =>
{
col.Add("OrderID", false).HeaderText("Order ID");
col.Add("RequiredDate", false).HeaderText("Required
Date");
col.Add("Freight", false). HeaderText("Freight");
col.Add("ShipName", false).HeaderText("Ship Name");
col.Add("ShipCountry", false).HeaderText("Ship
Country");
})
.Caption("Orders")
.EnablePaging()
.PageSettings(Page => Page.PageSize(12))
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Midnight)

%>

© 2014 Syncfusion. All rights reserved. 144 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]
@(Html.Syncfusion().Grid<System.Data.DataRow>("OrdersGrid")
.Datasource(Model)
.Column(col =>
{
col.Add("OrderID", false).HeaderText("Order ID");
col.Add("RequiredDate", false).HeaderText("Required
Date");
col.Add("Freight", false) .HeaderText("Freight ");
col.Add("ShipName", false).HeaderText("Ship Name");
col.Add("ShipCountry", false).HeaderText("Ship
Country");
})
.Caption("Orders")
.EnablePaging()
.PageSettings(Page => Page.PageSize(12))
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins. Midnight)

4. Set its data source and render the view.

[Controller]
public ActionResult Datatable()
{
return View(GetTable());
}

public DataTable GetTable()


{

var connection =
ConfigurationManager.ConnectionStrings["NORTHWNDConnectionString"].Conn
ectionString;
using (var dataAdapter = new SqlDataAdapter("SELECT * from
Orders", connection))
{
var dataTable = new DataTable();

dataAdapter.Fill(dataTable);
return dataTable;
}

© 2014 Syncfusion. All rights reserved. 145 | Page


Essential Grid for ASP.NET MVC Classic

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Datatable(PagingParams args)
{

return
GetTable().AsEnumerable().GridActions<System.Data.DataRow>();
}

1. Run the application. The grid will appear as shown below.

Figure 52: DataTable

© 2014 Syncfusion. All rights reserved. 146 | Page


Essential Grid for ASP.NET MVC Classic

4.2.10.2 Through GridPropertiesModel


1. Create a model in the application (refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<DataRow>("StudentGrid", "GridModel",
col =>
{
col.Add("OrderID", false).HeaderText("Order ID");
col.Add("RequiredDate", false).HeaderText("Required
Date");
col.Add("Freight", false);
col.Add("ShipName", false).HeaderText("Ship Name");
col.Add("ShipCountry", false);
}) %>

View [cshtml]

@( Html.Syncfusion().Grid<DataRow>("StudentGrid", "GridModel",
col =>
{
col.Add("OrderID", false).HeaderText("Order ID");
col.Add("RequiredDate", false).HeaderText("Required
Date");
col.Add("Freight", false);
col.Add("ShipName", false).HeaderText("Ship Name");
col.Add("ShipCountry", false);

}))

4. Create a GridPropertiesModel in the Index method. Bind the data source using the
Datasource property and pass the model from the controller to the view using the
ViewData class as given below.

[Controller]
public ActionResult Index()
{
GridPropertiesModel< DataRow > model = new
GridPropertiesModel< DataRow >()
{
DataSource = GetTable().AsEnumerable(),

© 2014 Syncfusion. All rights reserved. 147 | Page


Essential Grid for ASP.NET MVC Classic

Caption = "Orders",
AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
return
GetTable().AsEnumerable().GridActions<System.Data.DataRow>();
}

6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 148 | Page


Essential Grid for ASP.NET MVC Classic

Figure 53: DataTable


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Data Binding > DataTable Binding

4.2.11 JSON Binding to MVC Grid and Monitoring Changes with


Knockout.js
The flexibility of Syncfusion Grid’s client-side functionality. Here are the steps involved:

4.2.11.1 Grid preparation

In this case, we are choosing the JSON mode for the grid and Excel-like editing to ensure that the
grid is responding to JSON changes.

[View]

@{ Html.Grid<MvcSampleApplication.Models.EditableOrder>("Grid1")
........
........
.ClientSideEvents(c =>
c.QueryCellInfo("Grid1QueryCell") // This adds the
Data-bind attribute to a grid cell.
.OnActionComplete("ActionComplete")

© 2014 Syncfusion. All rights reserved. 149 | Page


Essential Grid for ASP.NET MVC Classic

.OnToolbarClickEvent("ToolbarClicked"))
........
........
.Render();
}

4.2.11.2 Knockout’s ViewModel

Knockout.js is the better choice for dynamic UI updates without any glue-code or events. Here,
the grid is bound with the “Editable Order” model from the server side. Since Knockout.js is
model-based, we have to create a model on the client side also. The code for that is as follows:

[Script]

function OrderViewModel(data) {

// Actual JSON from grid.


this.data = data;

// This is to detect changes in the model.


this.isDirty = ko.observable(false);

// Model properties.
this.OrderID = ko.observable().extend({ AutoUpdate: { "model":
this, "name": "OrderID" } });
this.CustomerID = ko.observable().extend({ AutoUpdate: { "model":
this, "name": "CustomerID" } });
this.EmployeeID = ko.observable().extend({ AutoUpdate: { "model":
this, "name": "EmployeeID" } });
this.Freight = ko.observable().extend({ AutoUpdate: { "model":
this, "name": "Freight" } });

// Created custom extender for auto-updating JSON data as well as the


model.

ko.extenders.AutoUpdate = function (target, options) {


target(options.model.data[options.name]);
target.subscribe(function (newValue) {

// Notifying the model that it has been changed.


if (!options.model.isDirty())
options.model.isDirty(true);

© 2014 Syncfusion. All rights reserved. 150 | Page


Essential Grid for ASP.NET MVC Classic

// Updating changed values to original JSON data.


options.model.data[options.name] = newValue;

return target;
}

AutoUpdate is the custom extender for observables; it will take care of syncing a JSON data
source between Knockout’s model and the grid’s data source.

We also need another model for storing the list of an OrderViewModel collection and binding it to
a page.

[Script]

function PageViewModel() {
this.dataSource = ko.observableArray([]);
}

4.2.11.3 Integrating the Grid and Knockout’s ViewModel

For the integration, we are going to write code for setting the data-bind attributes to a grid cell
and binding the grid’s HTML elements to Knockout.js.

The QueryCellInfo code adding the data-bind attribute is as follows:

[View]

function Grid1QueryCell(sender, args) {


if (args.Column.Name) {
var currentData = "dataSource()[" + args.Element.parentNode.rowIndex
+ "].";

// Here we set the Knockout.js data-binding attribute.


$(args.Element).attr("data-bind", "text: " + currentData +
args.Column.Name + ",css: {updatedCell : " + currentData + "isDirty}");
// text: is for updating cell values and
// css: is for notifying the user that cells have been updated.
}
}

For binding the model, we have to use the grid’s OnActionComplete event, since during initial
rendering the grid didn’t have data in it. Let me show you the code:

[Script]

// The grid's OnActionComplete event has been used to update Knockout’s

© 2014 Syncfusion. All rights reserved. 151 | Page


Essential Grid for ASP.NET MVC Classic

data source.
function ActionComplete(grid, args) {

// Here we are setting the page data source.


page.dataSource(ko.syncJsMap(grid.get_jsonModeMgr().get_dataSource(),
OrderViewModel));

// Clearing previous binding, if any.

ko.cleanNode($(grid.get_element()).find(".GridContent").children().get(
0));

// Applying bindings to newly created content.


ko.applyBindings(page,
$(grid.get_element()).find(".GridContent").children().get(0));
}

syncJsMap is the Knockout.js extension we are created for converting the JSON data source to
Knockout’s model-based data source. Here is the code I used:

[Script]

ko.syncJsMap = function (obj, viewModel) {


if (obj.length) {
var mapArray = [];
for (var i = 0; i < obj.length; i++) {
mapArray.push(new viewModel(obj[i]));
}
return mapArray;
}
}

4.2.11.4 Playing with the JSON Collection

We have written some HTML and JavaScript to produce the following functionality:

Upon clicking Change, the concerned JSON data will be updated using Knockout’s ViewModel.
The code for that is as follows:

© 2014 Syncfusion. All rights reserved. 152 | Page


Essential Grid for ASP.NET MVC Classic

[Script]

$("#butChange").click(function () {
var rowIndex = parseInt($("#rowIndex").val(), 10);
var columnName = $("#selectColumn").val()
var value = $("#change").val();

// The JSON collection can be changed like this. This will update
the grid's UI as well as the data source.
page.dataSource()[rowIndex][columnName](value);
});

Once Change is clicked, you’ll see the updates in the grid as well. Please refer to the following
screenshot:

You can see in the previous screenshot that the updated row will have a red mark. Click on the
save icon in the grid’s toolbar to store data in the database and clear all dirty items.

© 2014 Syncfusion. All rights reserved. 153 | Page


Essential Grid for ASP.NET MVC Classic

You can find a downloadable version of this sample here:


http://www.syncfusion.com/downloads/Support/DirectTrac/General/JsonCollection%20Change
576454545.zip

W ehave also written a blog pfor this functionality. Please refer to the following blog link:

http://www.syncfusion.com/blogs/post/JSON-Binding-to-MVC-Grid-and-Monitoring-Changes-with-
Knockoutjs.aspx

4.3 Paging
Essential Grid offers complete navigation support to easily switch between the pages using the
pager bar available at the bottom of the Grid control. It facilitates splitting up huge grid data and
displays viewable sets of Grid rows on each page. By selecting the respective page numbers you
can navigate to the other pages. You can also limit the number of pages.
The Grid control for MVC exposes the following properties and methods to enable and control the
paging feature.
Properties

Property Description Type of Value it Any other


property accepts dependencies/sub-
properties
associated
AllowPaging Enables the paging Boolean True/false NA
feature.

PageSize Sets the number of Int +ve Dependent on


records to be displayed in

© 2014 Syncfusion. All rights reserved. 154 | Page


Essential Grid for ASP.NET MVC Classic

a single grid page. The Integers AllowPaging


same number of records
will be available for the
next page and you will be
able to navigate between
these pages using the
pager bar.
Default page size is 12.

PageCount Sets the number of pages Int +ve Dependent on


to be displayed in the Integers AllowPaging
pager bar. You can limit
the number of pages to be
displayed using this
property.

Default page count is 10.

CurrentPage Set the current page to the Int +ve Dependent on


Grid control. Intergers AllowPaging

Methods

Method Descriptions Parameters Return type


EnablePaging() Used to enable the paging feature in the No parameter IGridBuilder<T>
Grid control.

AllowPaging(bool) Used to enable/disable the paging Enable as IPagerBuilder


feature. bool

PageSize(Int32) Sets the number of records to be Page size as IPagerBuilder


displayed in a single grid page. The integer
same number of records will be
available for the next page and you will
be able to navigate between these
pages using pager bars.

PageCount(Int32) Sets the number of pages to be Page count IPagerBuilder


displayed in the pager bar. You can limit as integer
the number of pages to be displayed
using this property.

CurrentPage(Int32) Set the current page to the Grid control. Current page IPagerBuilder
number as
integer

© 2014 Syncfusion. All rights reserved. 155 | Page


Essential Grid for ASP.NET MVC Classic

4.3.1 Server Mode


4.3.1.1 Through GridBuilder

1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View)
3. In the view you can use its Model property in Datasource() in order to bind the data
source.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship City");
})%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship City");
}.Render();
}

4. To enable the paging feature for your grid you should use the EnablePaging() method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.EnablePaging()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");

© 2014 Syncfusion. All rights reserved. 156 | Page


Essential Grid for ASP.NET MVC Classic

columns.Add(p => p.ShipCity).HeaderText("Ship City");


})%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.EnablePaging()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship City");
}).Render();
}
5. Set its data source and render the view.

Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}

6. In order to work with paging actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)

© 2014 Syncfusion. All rights reserved. 157 | Page


Essential Grid for ASP.NET MVC Classic

{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}

7. Run the application. The grid will appear as shown below.

Figure 54: Grid with Paging

4.3.1.1.1 Pager customization

 If you want to enable or disable the paging based on some condition, use the
AllowPaging(bool) method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.AllowPaging(true))
%>

 If you want to change the page size, use the PageSize(Int32) method.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.PageSettings(paging => paging.PageSize(20))
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")

© 2014 Syncfusion. All rights reserved. 158 | Page


Essential Grid for ASP.NET MVC Classic

.Datasource(Model)
.Caption("Orders Details")
.PageSettings(paging => paging.PageSize(20))
.Render();

 If you want to change the number of visible pages counted in the pager bar, use the
PageCount(Int32) method.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.PageCount(5))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.PageCount(5))
.Render();
}

 If you want to render the grid with initial paging, use the CurrentPage(Int32)
method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.CurrentPage(3))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)

© 2014 Syncfusion. All rights reserved. 159 | Page


Essential Grid for ASP.NET MVC Classic

.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.CurrentPage(3))
.Render();
}

4.3.1.2 Through GridPropertiesModel

1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("SortingGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("SortingGrid","GridModel", columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}))

© 2014 Syncfusion. All rights reserved. 160 | Page


Essential Grid for ASP.NET MVC Classic

4. Create a GridPropertiesModel in the Index method. Use the AllowPaging property to


enable the paging feature.

Controller
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource=new NorthwindDataContext().Orders,
Caption="Orders",
AllowPaging=true
};
ViewData["GridModel"] = gridModel; // Pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with paging actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Products;
return data.GridActions<Product>();
}

6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 161 | Page


Essential Grid for ASP.NET MVC Classic

Figure 55: Grid with Paging

4.3.1.2.1 Pager customization

 If you want to change the page size, use the PageSize property.
Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders Details",
AllowPaging = true,
PageSize=20
};

 If you want to change the number of visible pages counted in the pager bar, use the
PageCount property.
10.
Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders Details",
AllowPaging = true,
PageCount=5
};

 If you want to render the grid with initial paging, use the CurrentPage property.

© 2014 Syncfusion. All rights reserved. 162 | Page


Essential Grid for ASP.NET MVC Classic

Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders Details",
AllowPaging = true,
CurrentPage=3
};

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Paging > Server Mode

4.3.2 JSON Mode


4.3.2.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Enable paging using the EnablePaging method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnablePaging()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>

© 2014 Syncfusion. All rights reserved. 163 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnablePaging()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}

6. Render the view.

Controller
public ActionResult Index()
{
return View();
}

7. In order to work with paging actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code sample.

Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

8. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 164 | Page


Essential Grid for ASP.NET MVC Classic

Figure 56: Paging Enabled Grid

4.3.2.1.1 Pager Customization


 To enable or disable the paging based on some condition, use the AllowPaging(bool)
method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.PageSettings(paging => paging.AllowPaging(true))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.PageSettings(paging => paging.AllowPaging(true))
.Render();
}

 To change the page size, use the PageSize(Int32) method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")

© 2014 Syncfusion. All rights reserved. 165 | Page


Essential Grid for ASP.NET MVC Classic

.ActionMode(ActionMode.JSON)
.PageSettings(paging => paging.PageSize(20))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.PageSettings(paging => paging.PageSize(20))
.Render();
}

To change the number of visible pages counted in the pager bar, use the
PageCount(Int32) method.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.PageCount(5))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.EnablePaging()
.PageSettings(paging => paging.PageCount(5))
.Render();
}

 If you want to render the grid with initial paging, use the CurrentPage(Int32) method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.PageSettings(paging => paging.CurrentPage(3))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders Details")

© 2014 Syncfusion. All rights reserved. 166 | Page


Essential Grid for ASP.NET MVC Classic

.ActionMode(ActionMode.JSON)
.EnablePaging()
.PageSettings(paging => paging.CurrentPage(3))
.Render();
}

4.3.2.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
)

4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to set
JSON mode.
5. Use the AllowPaging property to enable the paging operations.

[Controller]

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
AllowPaging = true,
ActionMode = ActionMode.JSON

© 2014 Syncfusion. All rights reserved. 167 | Page


Essential Grid for ASP.NET MVC Classic

};

ViewData["GridModel"] = gridModel;
return View();
}

6. In order to work with paging actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

7. Run the application. The grid will appear as shown below.

Figure 57: Paging Enabled Grid

4.3.2.2.1 Pager Customization


 To change the page size, use the PageSize property.

Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()

© 2014 Syncfusion. All rights reserved. 168 | Page


Essential Grid for ASP.NET MVC Classic

{
ActionMode = ActionMode.JSON,
Caption = "Orders Details",
AllowPaging = true,
PageSize=20
};

 To change the number of visible pages counted in the pager bar, use the PageCount
property.

Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
ActionMode = ActionMode.JSON,
Caption = "Orders Details",
AllowPaging = true,
PageCount=5
};

 If you want to render the grid with initial paging, use the CurrentPage property.

Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
ActionMode = ActionMode.JSON,
Caption = "Orders Details",
AllowPaging = true,
CurrentPage=3
};

Sample Link
To view the samples, follow the steps below:
1. Open the ASP.NET MVC sample browser from the dashboard. (Refer to the Samples and
Location chapter)
2. Navigate to Grid>Paging>JSON Mode.
11.

4.3.3 Pager Customization

Essential Grid supports twelve different types of built-in pager styles. They are:
 Default
 Advanced
 DefaultAndAdvanced
 DefaultAndManual

© 2014 Syncfusion. All rights reserved. 169 | Page


Essential Grid for ASP.NET MVC Classic

 Manual
 Numeric
 PrevAndNext
 PrevNextAndAdvanced
 PrevNextAndManual
 Slider
 SliderAndAdvanced
 SliderAndManual

The position of the pager can be customized using the following four options:
 BottomLeft
 BottomRight
 TopLeft
 TopRight

Use Case Scenarios


The user can easily navigate pages using the twelve different types of pager styles. The position
of the pager can also be customized.

4.3.3.1 Customizing the Grid Pager in an Application

4.3.3.1.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Almond)
.Column(col =>
{
col.Add(c => c.OrderID)
col.Add(c => c.EmployeeID)
col.Add(c => c.ShipCountry)
col.Add(c => c.ShipCity;
col.Add(c => c.CustomerID);
})

.PageSettings(page =>

© 2014 Syncfusion. All rights reserved. 170 | Page


Essential Grid for ASP.NET MVC Classic

{
page.AllowPaging(true);
page.PagerStyle(PagerStyle.Slider);
page.PagerPosition(Position.TopLeft);
page.ShowPagerInformation(true);
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<MVCSampleBrowser.Models.Order>("OrderGrid")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Almond)
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.ShipCountry);
col.Add(c => c.ShipCity );
col.Add(c => c.CustomerID);
})

.PageSettings(page =>
{
page.AllowPaging(true);
page.PagerStyle(PagerStyle.Slider);
page.PagerPosition(Position.TopLeft);
page.ShowPagerInformation(true);
}).Render();

4. Set its data source and render the view.

Controller
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.ToList();
return View(data);
}

© 2014 Syncfusion. All rights reserved. 171 | Page


Essential Grid for ASP.NET MVC Classic

5. Run the application. The grid will appear as shown in the following screenshot.

Figure 58: Grid with Slider Pager

4.3.3.1.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%= Html.Syncfusion().Grid<Order>("OrderGrid", col=>


{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.ShipCountry);
col.Add(c => c.ShipCity );
col.Add(c => c.CustomerID);
}%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("OrderGrid", col=>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.ShipCountry);
col.Add(c => c.ShipCity );

© 2014 Syncfusion. All rights reserved. 172 | Page


Essential Grid for ASP.NET MVC Classic

col.Add(c => c.CustomerID);


})
)

4. Create a GridPropertiesModel in the Index method. Use the AllowGrouping property to


enable the grouping feature.
Controller

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AutoFormat = Skins.Sandune
};
gridModel.PageSetting.AllowPaging = true;
gridModel.PageSetting.PagerStyle = PagerStyle.Slider;
gridModel.PageSetting.PagerPosition = Position.TopLeft;
gridModel.PageSetting.ShowPagerInformation = true;
ViewData["OrderGrid"] = gridModel;
return View();
}

5. Run the application. The grid will appear as shown in the following screenshot:

Figure 59: Grid with Slider Pager

Properties

© 2014 Syncfusion. All rights reserved. 173 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it accepts Any other


property dependencies/s
ub-properties
associated
PagerStyle Gets or sets the pager Enum PagerStyle.Default NA
style for the grid. The
default value is Default.
PagerStyle.Advanced

PagerStyle.DefaultAn
dAdvanced

PagerStyle.DefaultAn
dManual

PagerStyle.Manual

PagerStyle.Numeric

PagerStyle.PrevAnd
Next

PagerStyle.PrevNext
AndAdvanced

PagerStyle.PrevNext
AndManual

PagerStyle.Slider

PagerStyle.SliderAnd
Advanced

PagerStyle.SliderAnd
Manual

© 2014 Syncfusion. All rights reserved. 174 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it accepts Any other


property dependencies/s
ub-properties
associated

PagerPositio Gets or sets the position of Enum Position.BottomLeft NA


n the pager. The default
Position.BottomRight
value is BottomLeft.
Position.TopLeft
Position.TopRight

SliderWidth Gets or sets the slider double double PagerStyle


width when PagerStyle is
set to Slider,
SliderAndManual, and
SliderAnd Advanced.

TextboxWidth Gets or sets the text box double double PagerStyle


width when PagerStyle is
set to Manual, Advanced,
DefaultAndManual,
DefaultAndAdvanced,
PrevNextAndManual,
PrevNextAndAdvanced,
SliderAndManual, and
SliderAnd Advanced.

ShowPagerIn Gets or sets the pager bool True/False NA


formation information to display or
not.

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Paging > Pager Types

© 2014 Syncfusion. All rights reserved. 175 | Page


Essential Grid for ASP.NET MVC Classic

4.4 Sorting
Sorting is defined as the process of arranging items/records in some ordered sequence. Essential
Grid supports arranging table data in ascending ( ) or descending ( ) order based on the
column header that is clicked. The order switches between ascending and descending each time
you click a column header for sorting.

Multi-sorting is enabled by setting the AllowMultiSorting property to True. It can also be


performed by holding CTRL and clicking the respective column headers.
The Grid control has the following properties and methods to enable sorting.

Properties

Property Description Type of Value Any other


property it dependencies/su
accept b-properties
s associated
AllowSorting Enables the bool True/Fals NA
sorting feature. e
Default value is
False.

SortDescriptors Collection that IList<SortDescripto Dependent on


is used to add r> AllowSorting.
sorted columns
programmatical
ly at initial load
with sort
directions.

AllowMultiSorting Enables bool True/Fals Dependent on


multicolumn e AllowSorting.
sorting. Setting
the value to
true, will allow
the user to sort
multiple
columns.
Default value is
False.

DisableSortedColum Collection that List<string> Dependent on


ns is used to AllowSorting.
disable the
sorting for

© 2014 Syncfusion. All rights reserved. 176 | Page


Essential Grid for ASP.NET MVC Classic

individual
columns.

Methods Description Paramet Return type


ers
EnableSorting() Used to No IGridBuilder<T>
enable the parameter
sorting feature
in Grid
control.

AllowSorting(bool) Used to Enable as ISortingBuilder


enable/disable bool <T>
the sorting
feature.

AllowMultiSorting (bool) Used to Enable as ISortingBuilder


enable bool <T>
multicolumn
sorting.
Setting the
value to true,
will allow the
user to sort
multiple
columns.

SortDescriptors(Action<IGridSortingColumnBuil Used to add Action ISortingBuilder


der<T>> sorted column method <T>
collections
programmatic
ally at initial
load with sort
directions.

4.4.1 Server Mode

4.4.1.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).

© 2014 Syncfusion. All rights reserved. 177 | Page


Essential Grid for ASP.NET MVC Classic

3. In the view you can use its Model property in Datasource() to bind the data source.
12.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}

4. To enable the sorting feature for your grid you should use the EnableSorting() method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")

© 2014 Syncfusion. All rights reserved. 178 | Page


Essential Grid for ASP.NET MVC Classic

.EnableSorting()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnableSorting()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}

5. Set its data source and render the view.

Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()

© 2014 Syncfusion. All rights reserved. 179 | Page


Essential Grid for ASP.NET MVC Classic

{
var data = new NorthwindDataContext().Orders;
return View(data);
}

6. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}

7. Run the application. The grid will appear as shown below.

Figure 60: Grid with Sorting

© 2014 Syncfusion. All rights reserved. 180 | Page


Essential Grid for ASP.NET MVC Classic

4.4.1.1.1 Sorting customization

 If you want to enable or disable the sorting based on some condition, use
AllowSorting(bool) method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings( sort => sort.AllowSorting(true))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings( sort => sort.AllowSorting(true))
.Render();
}

 If you want to enable or disable the multi-sorting feature use the


AllowMultiSorting(bool) method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings( sort => sort.AllowMultiSorting(true))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings( sort => sort.AllowMultiSorting(true))
.Render();
}

 If you want to render the grid with initial sorting, use the SortDescriptors() method.

© 2014 Syncfusion. All rights reserved. 181 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings(sort =>
sort. SortDescriptors(column => {
column.Add(c => c.CustomerID);
}
))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings(sort =>
sort. SortDescriptors(column => {
column.Add(c => c.CustomerID);
}
)).Render();
}

 If you want to render the grid with initial sorting in a specific direction, use the
SortDescriptors() method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.SortSettings(sort =>
sort. SortDescriptors(column => {
column.Add(c =>
c.CustomerID,System.ComponentModel.ListSortDirection.Descending); }
))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)

© 2014 Syncfusion. All rights reserved. 182 | Page


Essential Grid for ASP.NET MVC Classic

.Caption("Orders")
.EnablePaging()
.SortSettings(sort =>
sort. SortDescriptors(column => {
column.Add(c =>
c.CustomerID,System.ComponentModel.ListSortDirection.Descending); }
)).Render();
}

4.4.1.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("SortingGrid","GridModel", columns =>


{
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("SortingGrid","GridModel", columns =>
{
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}))

© 2014 Syncfusion. All rights reserved. 183 | Page


Essential Grid for ASP.NET MVC Classic

4. Create a GridPropertiesModel in the Index method. Use the AllowSorting property to


enable the sorting feature.

Controller

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource=new NorthwindDataContext().Orders,
Caption="Orders",
AllowPaging=true,
AllowSorting=true,
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = gridModel; // Pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code sample.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Products;
return data.GridActions<Product>();
}
6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 184 | Page


Essential Grid for ASP.NET MVC Classic

Figure 61: Grid with Sorting Feature

4.4.1.2.1 Sorting Customization

 If you want to enable or disable the multi-sort feature, use the AllowMultiSorting
property.
Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting=true,
AllowMultiSorting=true,
AutoFormat=Skins.Sandune
};

 If you want to render the grid with initial sorting use the SortDescriptors property.
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()

© 2014 Syncfusion. All rights reserved. 185 | Page


Essential Grid for ASP.NET MVC Classic

{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting=true,
AllowMultiSorting=true,
AutoFormat=Skins.Sandune
};

// Create SortDescriptor object and specify the column name


for initial sorting.
SortDescriptor sort = new SortDescriptor();
sort.ColumnName = "CustomerID";

// Add the SortDescriptor to the grid using SortDescriptors


property.
gridModel.SortDescriptors.Add(sort);

ViewData["GridModel"] = gridModel;
return View();
}

 If you want to render the grid with initial sorting with direction use the SortDescriptors
property.

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting=true,
AllowMultiSorting=true,
AutoFormat=Skins.Sandune
};

// Create SortDescriptor object and specify the column name


for initial sorting.
SortDescriptor sort = new SortDescriptor();
sort.ColumnName = "CustomerID";
// Specify the sort direction using the SortDirection
property.

© 2014 Syncfusion. All rights reserved. 186 | Page


Essential Grid for ASP.NET MVC Classic

sort.SortDirection =
System.ComponentModel.ListSortDirection.Descending;

// Add the SortDescriptor to the grid using the


SortDescriptors property.
gridModel.SortDescriptors.Add(sort);
ViewData["GridModel"] = gridModel;
return View();
}

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Sorting > Server Mode

4.4.2 JSON Mode


JSON (JavaScript Object Notation) is a lightweight data interchange format for the serialization of
structured data. It defines a small set of formatting rules for the portable representation of
structured data. It is human readable, platform independent, and has wide availability of
implementations. You can use this JSON format to exchange data in the MVC architecture.
Use Case Scenarios

13. High performance: The grid will be quickly rendered because of client-side rendering.
14. Encapsulation: Objects are encapsulated to another object for security.
15. Reduction of post back time: On the server side, rendering grid content does not happen
which will reduce the postback time.

4.4.2.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Enable sorting using the EnableSorting method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnableSorting()
.Column( columns => {

© 2014 Syncfusion. All rights reserved. 187 | Page


Essential Grid for ASP.NET MVC Classic

columns.Add(p => p.OrderID);


columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnableSorting()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}

6. Render the view.

Controller

public ActionResult Index()


{
return View();
}

7. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as shown in the code below.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

© 2014 Syncfusion. All rights reserved. 188 | Page


Essential Grid for ASP.NET MVC Classic

8. Run the application. The grid will appear as shown below.

Figure 62: Sorting Enabled Grid

© 2014 Syncfusion. All rights reserved. 189 | Page


Essential Grid for ASP.NET MVC Classic

Figure 63: “Order ID” Column Sorted in Descending Order

4.4.2.1.1 Sorting Customization

 To enable and disable the sorting feature use the AllowSorting(bool) method.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings( sort => sort.AllowSorting(true))
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)

© 2014 Syncfusion. All rights reserved. 190 | Page


Essential Grid for ASP.NET MVC Classic

.SortSettings( sort => sort.AllowSorting(true))


.Render();
}

 To enable or disable the multi-sorting feature, use the AllowMultiSorting(bool)


method.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings( sort => sort.AllowMultiSorting(true))
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings( sort =>
sort.AllowMultiSorting(true))
.Render();
}

 To render the grid with initial sorting, use the SortDescriptors() method.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings(sort =>
sort.SortDescriptors(column => {
column.Add(c => c.CustomerID);
}
))
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings(sort =>
sort.SortDescriptors(column => {
column.Add(c => c.CustomerID);
}
)).Render();
}

© 2014 Syncfusion. All rights reserved. 191 | Page


Essential Grid for ASP.NET MVC Classic

 To render the grid with initial sorting in a specific direction, use the
SortDescriptors() method.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings(sort =>
sort.SortDescriptors(column => {
column.Add(c =>
c.CustomerID,System.ComponentModel.ListSortDirection.Descending); }
))
%>
.

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.SortSettings(sort =>
sort.SortDescriptors(column => {
column.Add(c =>
c.CustomerID,System.ComponentModel.ListSortDirection.Descending); }
)).Render();
}

4.4.2.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {


columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>

© 2014 Syncfusion. All rights reserved. 192 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {


columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}))

4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to set
the JSON mode.
5. Use the AllowSorting property to enable the sorting operations.

[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
AllowSorting = true,
ActionMode = ActionMode.JSON

};

ViewData["GridModel"] = gridModel;
return View();
}

6. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code.

Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

7. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 193 | Page


Essential Grid for ASP.NET MVC Classic

Figure 64: Sorting Enabled Grid

© 2014 Syncfusion. All rights reserved. 194 | Page


Essential Grid for ASP.NET MVC Classic

Figure 65: “Order ID” Column Sorted in Descending Order

4.4.2.2.1 Sorting Customization

 To enable or disable the multi-sorting feature, use the AllowMultiSorting property.

Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
Caption = "Orders",
AllowSorting=true,
AllowMultiSorting=true,
ActionMode = ActionMode.JSON

};

© 2014 Syncfusion. All rights reserved. 195 | Page


Essential Grid for ASP.NET MVC Classic

 To render the grid with initial sorting, use the SortDescriptors property.

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AllowSorting=true,
AllowMultiSorting=true,
AutoFormat=Skins.Sandune
};

// Create SortDescriptor object and specify the column name


for initial sorting.
SortDescriptor sort = new SortDescriptor();
sort.ColumnName = "CustomerID";

// Add the SortDescriptor to the grid using SortDescriptors


property.
gridModel.SortDescriptors.Add(sort);

ViewData["GridModel"] = gridModel;
return View();
}

 To render the grid with initial sorting in a specific direction, use the SortDescriptors
property.

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AllowSorting=true,
AllowMultiSorting=true,
AutoFormat=Skins.Sandune
};

// Create SortDescriptor object and specify the column name


for initial sorting.
SortDescriptor sort = new SortDescriptor();
sort.ColumnName = "CustomerID";
// Specify the sort direction using the SortDirection
property.
sort.SortDirection =
System.ComponentModel.ListSortDirection.Descending;
// Add the SortDescriptor to the grid using SortDescriptors

© 2014 Syncfusion. All rights reserved. 196 | Page


Essential Grid for ASP.NET MVC Classic

property.
gridModel.SortDescriptors.Add(sort);
ViewData["GridModel"] = gridModel;
return View();
}

Sample Link
To view the samples, follow the steps below:

1. Open the ASP.NET MVC sample browser from the dashboard. (Refer to the Samples and
Location chapter)
2. Navigate to Grid>Sorting>JSON Mode.

4.5 Filtering

Essential Grid allows you to restrict the display of records using a mechanism called filters. A filter
facilitates the extraction of a subset of records that meet certain criteria. Filters can be applied to
one or more columns. This is very useful when dealing with large data sets. Essential Grid
provides both advanced filter and check box drop-down filter options by default.
When this feature is enabled, every column header displays a filter icon. Clicking this icon opens
a menu with a subset of check boxes in a drop-down list and submenu items for advanced
filtering.

Use Case Scenarios


This is very useful when dealing with large data sets. Users can apply filter values with multiple
choices. Using the Search box, users can find filter values easily.

Check Box Drop-Down List


Clicking on a filter icon opens a menu with a subset of check boxes in a drop-down list that holds
the possible filter values for the column clicked. To filter the data using a specific value, just select
the check box in the list that prefixes the desired filter value and click OK to apply the filters you
have selected. This will then reload the grid with only those records that have the selected value
in the column. The filter drop-down also provides a Select All option either to select or deselect
all the values at once.

Figure 66: Excel-Like Filters

© 2014 Syncfusion. All rights reserved. 197 | Page


Essential Grid for ASP.NET MVC Classic

Drop-Down Filters:
Clicking on a filter icon opens a menu with a subset of drop-down list items that holds the
possible filter values for the column clicked. To filter the data by a specific value, just select the
list box item that prefixes the desired filter value and click the OK button to apply filters. This will
then reload the grid with only those records that have the selected value in the column.

Figure 67: Grid with Drop-Down Filter Features

Advanced Filters:
Clicking on a filter icon opens a menu and submenu items. Submenu items in the filter menu
provide the advanced filtering options for end users. When selecting a sub menu item, a separate
dialog box opens and displays an advanced filter drop-down that lists the available filter operators
for the respective filtering column. Selecting a submenu item also provides text boxes that allow
you to type a filter string. It performs the filter operation by clicking the OK button.

Figure 68: Integer Filters

© 2014 Syncfusion. All rights reserved. 198 | Page


Essential Grid for ASP.NET MVC Classic

Figure 69: Custom Filter Options

This advanced filter option comes in three forms.


 Grid text filters—Can be used with any column type.
 Grid integer filters—Can be used with any numeric column type.
 Grid date-time filters—Can be used with any date-time column type.

Properties

Any other
dependenci
Type of
Property Description Value it accepts es/associat
property
ed sub-
properties
Enables the
grouping
AllowFiltering feature. boolean True/False NA
Default value is
False.

Collection that is
used to add and List<FilterD
apply filter escriptor> Dependent on
FilterDescriptors
conditions AllowFiltering.
programmaticall
y at initial load.

Gets or sets the


ColumnName column name for String NA
filter descriptor.

© 2014 Syncfusion. All rights reserved. 199 | Page


Essential Grid for ASP.NET MVC Classic

FilterType

.LessThan
FilterType .LessThanOrEqual

FilterType
.Equals

FilterType
Gets or sets the .NotEquals
Operator operator for a Enum
filter descriptor. FilterType
.GreaterThanOrEqual
FilterType

.GreaterThan
FilterType .StartsWith
FilterType .EndsWith
FilterType .Contains

Gets or sets the


Value value for a filter Object NA
descriptor.

Specifies the And


Predicate Enum NA
predicate type. Or

IsCaseSensitive Gets or sets the Bool True/False NA


value indicating
whether a filter
descriptor is
case sensitive.

FilterDropDownT It is used to Enum FilterDropDownType.SimpleList NA


ype configure the
FilterDropDownType.CheckList
filter drop-down
type.

Methods

Method Parameters Return type Descripti Refernce


ons links

© 2014 Syncfusion. All rights reserved. 200 | Page


Essential Grid for ASP.NET MVC Classic

EnableFilteri No parameter IGridBuilder<T> Used to


ng() enable the
filtering
feature in
Grid control

AllowFilter(b bool IGridColumnBuilder<T> Used to


ool) enable/disa
ble the filter
options for
individual
columns.

AllowFilterin (bool enable) GridFiltersBuilder<T> Used to NA


g enable or
disable the
filtering
feature

Filtering (Action<GridFilterBuilder IGridBuilder<T> Used to NA


<T> filters) configure
the Filtering
feature.

FilterDescrip (Action<GridFiltersBuilder GridFilterBuilder<T> Used to add Filtering


tors <T> descriptors) the initial
filter
descriptors
to grid.

Add Expression<Func<T,Tpro GridFilterDescriptorBuil Used to add FilterDescrip


perty>> expression der<T> the filter tors
column
name in the
filter
descriptor
instance.

FilterBy (FilterType type) GridFilterDescriptorBuil Used to FilterDescrip


der<T> configure tors
the current
filter
descriptor’s
filter type.

© 2014 Syncfusion. All rights reserved. 201 | Page


Essential Grid for ASP.NET MVC Classic

Filtervalue (object value) GridFilterDescriptorBuil Used to set FilterDescrip


der<T> the current tors
filter
descriptor’s
filter value.

Predicate (PredicateType GridFilterDescriptorBuil Used to set FilterDescrip


predicate) der<T> the current tors
filter
descriptor’s
predicate
type.

MatchCase (bool enable) GridFilterDescriptorBuil Used to FilterDescrip


der<T> enable/disa tors
ble the
case-
sensitive
option to
the current
filter
instance.

Sample Link
To view the samples:
1. Open the ASP.NET MVC sample browser from the dashboard (Refer to the Samples and
Location chapter).
2. Navigate to Grid>Filtering to browse the filtering demos.

4.5.1 Server Mode


4.5.1.1 Through GridBuilder
To add a filter to the application using GridBuilder:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use the Model property in Datasource() to bind the data source.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()

© 2014 Syncfusion. All rights reserved. 202 | Page


Essential Grid for ASP.NET MVC Classic

.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");

columns.Add(P => P.ShipCountry).HeaderText("Ship Country");


columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");

columns.Add(P => P.ShipCountry).HeaderText("Ship Country");


columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}

4. To enable the filtering feature for your grid, you should use the EnableFiltering() method.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Count

© 2014 Syncfusion. All rights reserved. 203 | Page


Essential Grid for ASP.NET MVC Classic

ry");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Count
ry");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}

5. Set its data source and render the view.

[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}

6. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code.

[Controller]
/// <summary>
/// Paging/sorting/filtering requests are mapped to this method
. This method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>

© 2014 Syncfusion. All rights reserved. 204 | Page


Essential Grid for ASP.NET MVC Classic

/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}

7. Run the application. The grid will appear as shown in the following screenshot.

Figure 70: Grid with Filter Option

4.5.1.1.1 Filter Customization

 If you want to enable or disable the filter based on some condition, use the
AllowFiltering(bool) method:

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.AllowFiltering(true);
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")

© 2014 Syncfusion. All rights reserved. 205 | Page


Essential Grid for ASP.NET MVC Classic

.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.AllowFiltering(true);
}).Render();
}

 If you want to enable or disable the filter options for individual columns, use the
AllowFilter(bool) method in column mapping.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(f
alse);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(f
alse);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();

© 2014 Syncfusion. All rights reserved. 206 | Page


Essential Grid for ASP.NET MVC Classic

 If you want to render the filter menu in a simple drop-down list, use the
FilterDropDownType() method.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDropDownType(FilterDropDownType.SimpleList)
;
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDropDownType(FilterDropDownType.SimpleList)
;
}).Render();
}

There are two ways to specify the initial filters information namely:
 Use the Filtering() method to add the initial filters.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDescriptors(descriptor =>
{
descriptor.Add(c => c.EmployeeID).FilterBy(FilterType.Equals).F

© 2014 Syncfusion. All rights reserved. 207 | Page


Essential Grid for ASP.NET MVC Classic

ilterValue(5);
});
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(f
alse);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDescriptors(descriptor =>
{
descriptor.Add(c => c.EmployeeID).FilterBy(FilterType.Equals).F
ilterValue(5);
});
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(f
alse);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}

 Through GridPropertiesModel
a. Create GridPropertiesModel in Controller Index action and add the initial filters
using the FilterDescriptors property.

[Controller]

© 2014 Syncfusion. All rights reserved. 208 | Page


Essential Grid for ASP.NET MVC Classic

GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Order>(


);

// Apply intial filters to the grid.


gridModel.Filters.FilterDescriptors.Add(new FilterDescriptor() { Colu
mnName = "EmployeeID", Operator = Syncfusion.Linq.FilterType.Equals, Va
lue = 5 });

b. Pass the GridPropertiesModel to the view using the ViewData() method. Use the grid’s
ID as the key in ViewData.
[Controller]

GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Order>(


);

// Apply intial filters to the grid.


gridModel.Filters.FilterDescriptors.Add(new FilterDescriptor() { Colu
mnName = "EmployeeID", Operator = Syncfusion.Linq.FilterType.Equals, Va
lue = 5 });

//Pass the GridPropertiesModel to grid using GridID. Here F


ilterGrid is the grid's ID.
ViewData["FilterGrid"] = gridModel;

4.5.1.2 Through GridPropertiesModel


To add a filter to the application using GridPropertiesModel:

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
16. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel", columns =
> {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
})%>

© 2014 Syncfusion. All rights reserved. 209 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@( Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
}))

4. Create a GridPropertiesModel in the Index method. Use the AllowFiltering property to


enable the filtering feature.

[Controller]

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Filtering()
{
GridPropertiesModel<Order> gridModel = new GridPropertiesMo
del<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowFiltering = true,
AutoFormat = Skins.Sandune
};
ViewData["GridModel"] = gridModel;
return View();
}

5. In order to work with filtering actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.

[Controller]

/// <summary>
/// Paging requests are mapped to this method. This method invo
kes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>

© 2014 Syncfusion. All rights reserved. 210 | Page


Essential Grid for ASP.NET MVC Classic

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Filtering(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}

6. Run the application. The grid will appear as shown in the following screenshot.

Figure 71: Grid with Filter Option

4.5.1.2.1 Filter Customization


 If you want to enable or disable the filtering options for individual columns, then use the
AllowFilter(bool) method in column mapping.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel", columns =
> {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFil
ter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFil
ter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");

© 2014 Syncfusion. All rights reserved. 211 | Page


Essential Grid for ASP.NET MVC Classic

columns.Add(p => p.OrderDate).HeaderText("Order Date").Form


at("{0:dd-MM-yyyy}");
}))

 If you want to render the filter menu in a simple drop-down list, then use the
FilterDropDownType property.

[Controller]
// Create GridPropertiesModel.
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>();

// Specify the drop-down type.


gridModel.Filters.FilterDropDownType = FilterDropDownType.SimpleL
ist;

 If you want to render the grid with initial filtering, add the filter conditions using the
FilterDescriptors property.

[Controller]
// Create GridPropertiesModel.
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>();

// Specify the drop-down type.


gridModel.Filters.FilterDropDownType = FilterDropDownType.SimpleL
ist;

 If you want to render the grid with initial filtering, add the filter conditions using the
FilterDescriptors property.

[Controller]

public ActionResult Filtering1()


{
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Ord
er>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,

© 2014 Syncfusion. All rights reserved. 212 | Page


Essential Grid for ASP.NET MVC Classic

AllowFiltering = true,
AutoFormat = Skins.Sandune
};
// Apply intial filters to the grid.
gridModel.Filters.FilterDescriptors.Add(new FilterDescriptor() { C
olumnName = "EmployeeID", Operator = Syncfusion.Linq.FilterType.Equals,
Value = 5 });

ViewData["GridModel"] = gridModel;
return View();
}

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Filtering > Server Mode

4.5.2 JSON Mode

4.5.2.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Enable filtering using the EnableFiltering() method.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnableFiltering()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>

© 2014 Syncfusion. All rights reserved. 213 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.EnableFiltering()
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}

6. Render the view.

Controller

public ActionResult Index()


{
return View();
}

7. In order to work with filtering actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code sample.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

8. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 214 | Page


Essential Grid for ASP.NET MVC Classic

Figure 72: Filtering Enabled Grid

4.5.2.1.1 Filter Customization

 To enable or disable filtering based on some condition, use the AllowFiltering(bool)


method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.AllowFiltering(true);
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.AllowFiltering(true);
}).Render();}

© 2014 Syncfusion. All rights reserved. 215 | Page


Essential Grid for ASP.NET MVC Classic

 To enable or disable filter options for individual columns, use the AllowFilter(bool)
method in column mapping.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(false)
;
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(false)
;
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}

 To render the filter menu in a simple drop-down list, use the FilterDropDownType()
method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")

.Caption("Orders")
.Filtering(filter =>
{
filter.FilterDropDownType(FilterDropDownType.SimpleList);
})

© 2014 Syncfusion. All rights reserved. 216 | Page


Essential Grid for ASP.NET MVC Classic

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")

.Caption("Orders")
.Filtering(filter =>
{
filter.FilterDropDownType(FilterDropDownType.SimpleList);
}).Render();
}

 Use the Filtering() method to add initial filters.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDescriptors(descriptor =>
{
descriptor.Add(c => c.EmployeeID).FilterBy(FilterType.Equals).FilterValue(5);
});
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID"); col
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Filtering(filter =>
{
filter.FilterDescriptors(descriptor =>

© 2014 Syncfusion. All rights reserved. 217 | Page


Essential Grid for ASP.NET MVC Classic

{
descriptor.Add(c => c.EmployeeID).FilterBy(FilterType.Equals).FilterValue(5);
});
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID"); col
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}

4.5.2.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {


columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}))

4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to


set the JSON mode.
5. Use the AllowFiltering property to enable the filtering operations.

© 2014 Syncfusion. All rights reserved. 218 | Page


Essential Grid for ASP.NET MVC Classic

[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
AllowFiltering = true,
ActionMode = ActionMode.JSON

};

ViewData["GridModel"] = gridModel;
return View();
}

6. To work with filtering actions, create a Post method for Index actions and bind the data
source to the grid as given in the below code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

7. Run the application. The grid will appear as shown below:

Figure 73: Filtering Enabled Grid

© 2014 Syncfusion. All rights reserved. 219 | Page


Essential Grid for ASP.NET MVC Classic

4.5.2.2.1 Filter Customization

 To enable or disable the filtering options for individual columns, use the
AllowFilter(bool) method in column mapping.
View[ASPX]

<%=Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel", columns =
> {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFil
ter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("FilteringGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowFil
ter(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
}))

 To render the filter menu in a simple drop-down list, use the FilterDropDownType
property.
[Controller]

// Create the GridPropertiesModel.


GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>();

// Specify the drop-down type.


gridModel.Filters.FilterDropDownType = FilterDropDownType.SimpleL
ist;

 To render the grid with the initial filtering, add filter conditions using the FilterDescriptors
property.

[Controller]

© 2014 Syncfusion. All rights reserved. 220 | Page


Essential Grid for ASP.NET MVC Classic

// Create the GridPropertiesModel.


GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>();

// Specify the drop-down type.


gridModel.Filters.FilterDropDownType = FilterDropDownType.SimpleL
ist;

 To render the grid with initial filtering, add the filter conditions using the FilterDescriptors
property.

[Controller]

public ActionResult Filtering1()


{
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Ord
er>()
{

ActionMode = ActionMode.JSON,
Caption = "Orders",
AllowFiltering = true,
AutoFormat = Skins.Sandune
};

// Apply intial filters to the grid.


gridModel.Filters.FilterDescriptors.Add(new FilterDescriptor() { C
olumnName = "EmployeeID", Operator = Syncfusion.Linq.FilterType.Equals,
Value = 5 });

ViewData["GridModel"] = gridModel;
return View();
}

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Filtering > JSON Mode

4.5.3 Filter Bar

The filter bar feature allows the grid to filter records with different expressions depending upon
the column type. The filter bar will be displayed at the top of the grid below the header row.

© 2014 Syncfusion. All rights reserved. 221 | Page


Essential Grid for ASP.NET MVC Classic

The filter bar allows you to filter expressions and get the data you want to filter by manually
entering data, unlike the default filter. This allows you to filter the values you want, with ease.

The following figure gives you a basic idea of the appearance of the filter bar in the MVC grid:

Figure 74: Grid with Filter Bar and Filter Status Message Bar

Use Case Scenario


The user can filter data quickly by entering the filter expressions manually in the filter bar.
This feature is very user friendly to advanced users, as the following filter options are available
with this feature:
 "<", ">", ">=", ">=", "=" for integer, double, decimal, date-time data columns
 "*value" (contains value), "%value" (ends with value),"value%" (begins with value) for
string data columns
 "1"(true), "0"(false) for Boolean data columns
 "Expression1 and Expression2", "Expression1 or Expression2" for all data columns

4.5.3.1 Properties

Type of Value it
Property Description Dependencies
property accepts

FilterMode This property Default NA


FilterMode
specifies the filter

© 2014 Syncfusion. All rights reserved. 222 | Page


Essential Grid for ASP.NET MVC Classic

Type of Value it
Property Description Dependencies
property accepts
mode. enum FilterBar

This property
specifies whether Depends on FilterMode—
FilterBarMod OnEnter
the filter data will
FilterBarMode be rendered e enum Immediate If FilterMode is set to
immediately or FilterBar, then FilterBarMode
after pressing the is activated.
ENTER key.

This property Depends on FilterMode—


ShowFilterBar specifies whether
StatusMessag the status If FilterMode is set to
e bool True or False FilterBar, then
message will be
displayed in the ShowFilterBarStatusMessag
grid or not. e is activated.

Depends on
ShowFilterBarStatusMessag
e—
FilterStatusBa Specifies the
rWidth Any integer Only if
width of the filter int
value ShowFilterBarStatusMessag
status bar.
e is enabled,
FilterStatusBarWidth is
enabled.

4.5.3.2 Filter Tokens


These are the filter tokens that should be used for filtering values:

Examples
Filter token (should be used as Description Used at
shown below)

value% StartsWith AlphaNumeric


%
%value EndsWith AlphaNumeric

*value

* value* Contains AlphaNumeric


*value*

© 2014 Syncfusion. All rights reserved. 223 | Page


Essential Grid for ASP.NET MVC Classic

Examples
Filter token (should be used as Description Used at
shown below)

< <value LessThan Numeric & DateTime

<= <=value LessThanOrEqual Numeric & DateTime

> >value GreaterThan Numeric & DateTime

>= >=value GreaterThanOrEqual Numeric & DateTime

= =value Equals Numeric & DateTime

! !value Not Equals Numeric & DateTime

>value and <=value


>value and <value
And (or) && Between Numeric & DateTime
>=value && <value

>=value && <=value

>value or <=value
>value or <value
Or (or) || Between Numeric & DateTime
>=value || <value
>=value || <=value

0 0 Equals Boolean

1 1 Equals Boolean

Note: Values can be entered in any format (not case sensitive).

4.5.3.3 Adding the Filter Bar to an MVC Grid


The grid can be rendered in two ways in MVC:

4.5.3.3.1 Through GridBuilder


1. Create a model in the application.
2. Create a strongly typed view.
3. In the view you can use its Model property in Datasource() to bind the data source.

© 2014 Syncfusion. All rights reserved. 224 | Page


Essential Grid for ASP.NET MVC Classic

4. To enable the filter bar filtering mode, set the FilterMode enum property to FilterBar. The
filter bar status message can be viewed by enabling the property
ShowFilterStatusMessage. The filter bar mode can be set to Immediate or OnEnter by
setting the enum property FilterBarMode.

The ASPX and Razor codes given below will help you customize the grid:
View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID").AllowFilter(false);
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Price").Format("{0:c}");

})

.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune).EnableGrouping()
.Filtering(filter =>
{
filter.AllowFiltering(true);
// Specifies the filter mode.

filter.FilterMode(FilterMode.FilterBar);
// Specifies the filter bar
mode.

filter.FilterBarMode(FilterBarMode.Immediate);
// Specifies whether the filter
status message will be shown.

filter.ShowFilterStatusMessage(true);
})

%>

View[cshtml]

@{Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)

© 2014 Syncfusion. All rights reserved. 225 | Page


Essential Grid for ASP.NET MVC Classic

.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID").AllowFilter(false);
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Price").Format("{0:c}");

})

.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune).EnableGrouping()
.Filtering(filter =>
{
filter.AllowFiltering(true);
// Specifies the filter mode.

filter.FilterMode(FilterMode.FilterBar);
// Specifies the filter bar
mode.

filter.FilterBarMode(FilterBarMode.Immediate);
// Specifies whether the filter
status message will be shown.

filter.ShowFilterStatusMessage(true);
})

.Render();

5. Set its data source and render the view.

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);

© 2014 Syncfusion. All rights reserved. 226 | Page


Essential Grid for ASP.NET MVC Classic

6. In order to work with filter actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code:

Controller

<summary>
/// Paging, editing, and filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

7. Run the application and use the filtering tokens in the filter bar to filter the data table. The
valid tokens are listed in the filter token table.
The following image is an output sample of a filter bar implemented in a grid:

Figure 75: Implementation of Filter Bar through GridBuilder

4.5.3.3.2 Through GridProperties model


1. Create a model in the application.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).

© 2014 Syncfusion. All rights reserved. 227 | Page


Essential Grid for ASP.NET MVC Classic

3. Add the following code in the Index.aspx file to create the Grid control in the view.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
})%>

View[cshtml]

@{Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
}).Render();
)}

4. Create a GridPropertiesModel in the Index actions.


5. To enable the FilterBar filtering mode, set the FilterMode to FilterBar as shown in the
code samples below:
17.
The following controller code will help you customize the Grid.

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
AllowPaging = true,

© 2014 Syncfusion. All rights reserved. 228 | Page


Essential Grid for ASP.NET MVC Classic

AllowSorting = true,
AllowFiltering = true,
AutoFormat = Skins.Sandune
};
gridModel.Filters.FilterMode = FilterMode.FilterBar;
gridModel.Filters.FilterBarMode = FilterBarMode.Immediate;
gridModel.Filters.ShowFilterStatusMessage = true;
ViewData["GridModel"] = gridModel;
return View();
}

/// <summary>
/// Paging, editing, and filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

6. Run the application and use the filtering tokens in the filter bar to filter the data table. The
valid tokens are listed in the filter token table.
18. The following figure is an output sample of a filter bar implemented in a grid.

Figure 76: Implementation of Filter Bar through GridPropertiesModel

© 2014 Syncfusion. All rights reserved. 229 | Page


Essential Grid for ASP.NET MVC Classic

4.5.3.4 How to Filter Data Using Filter Tokens in the Filter Bar
Filter tokens are the symbols that are used in filter expressions to filter data as you require.
Refer to Filter Tokens to learn more about them.
Use these filter tokens in the filter bar as necessary to filter data according to your needs.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Filtering > FilterBar

4.5.4 Searching
The searching feature is used to search for text in the data displayed in the grid. A Search text
box and Search button can be configured through toolbar items. This works similar to the Find
functionality in text editor applications. Users can effectively use this feature for finding the
searched strings.

Use Case Scenarios


This is very useful when dealing with large data sets. Using the Search box, users can find filter
values easily.

4.5.4.1 Through GridBuilder


To add the Search text box to the grid through GridBuilder:
1. Create a model in the application (refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (refer to How to > Strongly Typed View).
3. In the view, you can use its Model property in Datasource() to bind the data source.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>

© 2014 Syncfusion. All rights reserved. 230 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render(); }

4. To activate the search feature in the view, set the AllowSearching property to True.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.AllowSearching(true)
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)

© 2014 Syncfusion. All rights reserved. 231 | Page


Essential Grid for ASP.NET MVC Classic

.Caption("Orders")
.AllowSearching(true)
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}) )

5. If you want to enable or disable the search options for individual columns, use the
AllowSearching(bool) method in column mapping.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {

columns.Add(p => p.OrderID).HeaderText("Order ID").AllowSearchin


g(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("SearchingGrid")
.Datasource(Model)

© 2014 Syncfusion. All rights reserved. 232 | Page


Essential Grid for ASP.NET MVC Classic

.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").
AllowSearching(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country")
;
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}).Render();
}

6. Set its data source and render the view.

Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}

7. In order to work with searching actions, create a Post method for Index actions and
bind the data source to the grid as shown in the following code.
Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{

© 2014 Syncfusion. All rights reserved. 233 | Page


Essential Grid for ASP.NET MVC Classic

IEnumerable data = new NorthwindDataContext().Orders;


return data.GridActions<Order>();
}

8. Run the application. The grid will appear as shown below.

Figure 77: Grid with Search Text Box

4.5.4.2 Through GridPropertiesModel


To dynamically bind data to the grid through GridPropertiesModel:
1. Create a model in the application (Refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View[ASPX]

<%=Html.Syncfusion().Grid<Order>("SearchingGrid", "GridModel", column


=>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
})%>

© 2014 Syncfusion. All rights reserved. 234 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]

@(Html.Syncfusion().Grid<Order>("SearchingGrid", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
}))

 If you want to enable or disable the filtering options for individual columns, then use the
AllowSearching(bool) method in column mapping.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("SearchingGrid","GridModel", columns =
> {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowSea
rching(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
})%>

View [cshtml]

@(Html.Syncfusion().Grid<Order>("SearchingGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID").AllowSea
rching(false);
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date").Form
at("{0:dd-MM-yyyy}");
}))

4. Create a GridPropertiesModel in the Index actions.

© 2014 Syncfusion. All rights reserved. 235 | Page


Essential Grid for ASP.NET MVC Classic

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
// set AllowSearching as true to activate searching feature.
AllowSearching = true,
AutoFormat=Skins.Sandune
};

ViewData["GridModel"] = model; // Pass the model from


controller to view using ViewData.

 Essential Grid allows searching records through grid toolbar items. In this example,
Search button has been added as toolbar items in the code sample displayed below.

Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();

toolbar.Enable = true;

// Add the add new, edit, delete, save, cancel button in


toolbar.

toolbar.Items.Add(new ToolbarOptions() { ItemType=


GridToolBarItems.Search});
model.ToolBar = toolbar;

5. Run the application, The Grid will appear as shown below:

© 2014 Syncfusion. All rights reserved. 236 | Page


Essential Grid for ASP.NET MVC Classic

Figure 78: Searching through GridPropertiesModel

Sample Link
To view the samples, follow the steps below:
1. Open the Essential Grid sample browser from the dashboard. (Refer to the Samples and
Location chapter)
2. Navigate to Grid.MVC > Filtering > Searching

4.6 Grouping
4.6.1 Server Mode
Grouping is defined as the act or process of consolidating grid data into groups. Grouping allows
the categorization of records based on specified columns. You can easily group by a particular
column by simply dragging the column to the upper portion of the grid. The grid data is
automatically grouped when you drop a particular column. You are also able to expand a grouped
record by clicking the icon beside the grouped record.
The Grid control has the following properties and methods which enable and control the grouping
feature.
Properties

Property Description Type of Value it Any other


property accepts dependencies/sub-
properties
associated
AllowGrouping Enables the grouping bool True/False NA

© 2014 Syncfusion. All rights reserved. 237 | Page


Essential Grid for ASP.NET MVC Classic

feature.
Default value is
False.

GroupDescriptors Collection that is List<string> Dependent on


used to add grouped AllowGrouping.
columns
programmatically at
initial load.

Methods

Method Parameters Return type Descriptions


EnableGrouping() No parameter IGridBuilder<T> Used to enable
the grouping
feature in the
Grid control.

AllowGrouping(bool) Enable as bool IGroupingBuilder< Used to


T> enable/disable
the grouping
feature.

Groups Action<IGroupingBuilder<T IGroupingBuilder< Used to add


(Action<IGroupingBuilder< >> T> the grouped
T>) columns
collection
programmatical
ly at initial load.

4.6.1.1 Through GridBuilder


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()

© 2014 Syncfusion. All rights reserved. 238 | Page


Essential Grid for ASP.NET MVC Classic

.Column( columns => {


columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}

4. To enable the grouping feature for your grid you should use the EnableGrouping() method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {

© 2014 Syncfusion. All rights reserved. 239 | Page


Essential Grid for ASP.NET MVC Classic

columns.Add(p => p.OrderID).HeaderText("Order


ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}

5. Set its data source and render the view.

Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}

6. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.

© 2014 Syncfusion. All rights reserved. 240 | Page


Essential Grid for ASP.NET MVC Classic

Controller

/// <summary>
/// Paging and sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}

7. Run the application. The grid will appear as shown below.

Figure 79: Grid with Grouping Enabled

Drag and drop any columns in the group drop area. After grouping, the grid will appear as shown
below.

© 2014 Syncfusion. All rights reserved. 241 | Page


Essential Grid for ASP.NET MVC Classic

Figure 80: Grid with Grouped Column

4.6.1.1.1 Grouping Customization


If you want to enable or disable the grouping based on some condition, use the
AllowGrouping(bool) method.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Grouping( group => group.AllowGrouping(true))
%>
1. If you want to render the grid with the initial grouping, use
GroupDescriptors() method.
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Grouping(group =>
{
group.GroupDescriptors(cols => cols.Add(c =>
c.CustomerID));
})

%>

© 2014 Syncfusion. All rights reserved. 242 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Grouping( group => group.AllowGrouping(true))
}
2. If you want to render the grid with the initial grouping, use
GroupDescriptors() method.
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.Grouping(group =>
{
group.GroupDescriptors(cols => cols.Add(c =>
c.CustomerID));
}).Render();

4.6.1.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("GroupingGrid","GridModel"
, columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>

© 2014 Syncfusion. All rights reserved. 243 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]
@( Html.Syncfusion().Grid<Order>("GroupingGrid","GridModel", columns =>
{
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}))

4. Create a GridPropertiesModel in the Index method. Use AllowGrouping property to


enable the grouping feature.

Controller

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource=new NorthwindDataContext().Orders,
Caption="Orders",
AllowPaging=true,
AllowSorting=true,
AllowMultiSorting=true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = gridModel; // Pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with grouping actions, create a Post method for Index actions and bind the
data source to the grid as done in the following code sample.

Controller

/// <summary>
/// Paging, sorting, and grouping requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid. The required response is generated.

© 2014 Syncfusion. All rights reserved. 244 | Page


Essential Grid for ASP.NET MVC Classic

/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data.GridActions<Order>();
}

6. Run the application. The grid will appear as shown below.

Figure 81: Grid with Grouping Enabled

Drag and drop any columns in the group drop area. After grouping, the grid will appear as shown
below.

© 2014 Syncfusion. All rights reserved. 245 | Page


Essential Grid for ASP.NET MVC Classic

Figure 82: Grid with Grouped Column

4.6.1.2.1 Grouping Customization

 If you want to render the grid with initial grouping, use the GroupDescriptors property.

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowMultiSorting = true,
AllowGrouping = true,
AutoFormat = Skins.Sandune
};

// Add the grouped columns to the grid using


GroupDescriptors.

© 2014 Syncfusion. All rights reserved. 246 | Page


Essential Grid for ASP.NET MVC Classic

gridModel.GroupDescriptors.Add("CustomerID");

ViewData["GridModel"] = gridModel;
return View();
}

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Grouping > Server Mode

4.6.2 JSON Mode

4.6.2.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. To enable the grouping feature for your grid you should use the EnableGrouping() method.

View [ASPX]

<%= Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}) %>

© 2014 Syncfusion. All rights reserved. 247 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.ShipCity).HeaderText("Ship
City");
}).Render();
}

6. Render the view.

Controller

public ActionResult Index()


{
return View();
}

7. In order to work with grouping actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

8. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 248 | Page


Essential Grid for ASP.NET MVC Classic

Figure 83: Grid with Grouping Enabled

Drag and drop any columns in the group drop area. After grouping, the grid will appear as shown
below.

Figure 84: Grid with Grouped Column

© 2014 Syncfusion. All rights reserved. 249 | Page


Essential Grid for ASP.NET MVC Classic

4.6.2.1.1 Grouping Customization


If you want to enable or disable the grouping based on some condition, use the
AllowGrouping(bool) method.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Grouping( group => group.AllowGrouping(true))
%>
1. If you want to render the grid with the initial grouping, use
GroupDescriptors() method.
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Grouping(group =>
{
group.GroupDescriptors(cols => cols.Add(c =>
c.CustomerID));
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()
.Grouping( group => group.AllowGrouping(true))
}
2. If you want to render the grid with the initial grouping, use
GroupDescriptors() method.
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.EnablePaging()
.EnableSorting()

© 2014 Syncfusion. All rights reserved. 250 | Page


Essential Grid for ASP.NET MVC Classic

.Grouping(group =>
{
group.GroupDescriptors(cols => cols.Add(c =>
c.CustomerID));
}).Render();

4.6.2.2 Through GridPropertiesModel


1. Create a model in the application (refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {


columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}))

4. Create a GridPropertiesModel in the Index method. Use AllowGrouping property to


enable the grouping feature.
Controller

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource=new NorthwindDataContext().Orders,
Caption="Orders",
AllowPaging=true,

© 2014 Syncfusion. All rights reserved. 251 | Page


Essential Grid for ASP.NET MVC Classic

ActionMode=ActionMode.JSON,
AllowSorting=true,
AllowMultiSorting=true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = gridModel; // Pass the model from
controller to view using ViewData.
return View();
}

5. In order to work with grouping actions, create a Post method for Index actions and bind the
data source to the grid as done in the following code sample.

Controller

/// <summary>
/// Paging, sorting, and grouping requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders;
return data. GridJSONActions<Order>();
}

6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 252 | Page


Essential Grid for ASP.NET MVC Classic

Figure 85: Grid with Grouping Enabled

Drag and drop any columns in the group drop area. After grouping, the grid will appear as shown
below.

Figure 86: Grid with Grouped Column

© 2014 Syncfusion. All rights reserved. 253 | Page


Essential Grid for ASP.NET MVC Classic

4.6.2.2.1 Grouping Customization

 If you want to render the grid with initial grouping, use the GroupDescriptors property.
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
ActionMode=ActionMode.JSON,
AllowMultiSorting = true,
AllowGrouping = true,
AutoFormat = Skins.Sandune
};

// Add the grouped columns to the grid using


GroupDescriptors.
gridModel.GroupDescriptors.Add("CustomerID");

ViewData["GridModel"] = gridModel;
return View();
}

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Grouping > JSON Mode

4.7 Editing

Essential Grid has built-in support for editing grid content. This can be achieved by defining a
GridEditing class for the grid. Using this class, you can specify the action mappers for insert,
edit, update, delete, and cancel requests.
Key Features
The key features of editing are as follows:

© 2014 Syncfusion. All rights reserved. 254 | Page


Essential Grid for ASP.NET MVC Classic

 Allows nine modes of editing, such as inline row editing, inline form editing, inline custom
template form editing, dialog editing, dialog custom template form editing, external form
editing, external custom template form editing, auto excel editing, and manual editing.
 Enables MVC 4.0 client validation.
 Provides toolbar support for editing records.

Properties

Any other
dependenc
Type of
Property Description Value it accepts ies/sub-
property
properties
associated
Editing Gets or sets
the editing
properties for Class NA NA
the Grid
control.

AllowNew Used to
enable or
disable the
bool True/False NA
insert action in
the editing
mode.

AllowEdit Used to
enable or
disable the
bool True/False NA
edit action in
the editing
mode.

AllowDelete Used to
enable or
disable the
bool True/False NA
delete action
in the editing
mode.

DeleteMapper Gets or sets


the action
string Delete action name NA
mapper for the
delete action.

InsertMapper Gets or sets string Insert action name NA

© 2014 Syncfusion. All rights reserved. 255 | Page


Essential Grid for ASP.NET MVC Classic

Any other
dependenc
Type of
Property Description Value it accepts ies/sub-
property
properties
associated
the action
mapper for the
insert actions.

GridSaveMapper Gets or sets


the action
string Save action name NA
mapper for the
update action.

EditMode Gets or sets GridEditMode.AutoExcel


the edit mode
GridEditMode.Dialog
for editing.
GridEditMode.DialogTemplate
GridEditMode.ExternalForm
GridEditMode.ExternalFormTemplate
Enum NA
GridEditMode.InlineForm
GridEditMode.InlineTemplateForm

GridEditMode.ManualExcel
GridEditMode.Normal

FormModeEditor Gets or sets


Template the partial
view name for
the string Any partial view name NA
InlineTemplate
Form mode
editing.

Toolbar Gets or sets


the toolbar for Class NA NA
grid.

Enable Used to
enable or
disable the Bool True/False NA
toolbar in grid.

© 2014 Syncfusion. All rights reserved. 256 | Page


Essential Grid for ASP.NET MVC Classic

Any other
dependenc
Type of
Property Description Value it accepts ies/sub-
property
properties
associated
Items Used to add
List<Toolba
the items to Any toolbar items NA
rOptions>
grid toolbars.

AllowEditing Gets or sets


the particular
column
Bool True/False NA
enabling and
disabling
editing.

The following table illustrates the default CellEditTypes and their corresponding controls for
specific data types.

Data Type Default CellEditType Control


String CellEditType.StringEdit TextBox control

Boolean CellEditType.BooleanEdit CheckBox control

Integer CellEditType.NumericEdit NumericTextBox control

Decimal CellEditType.NumericEdit NumericTextBox control with


default two decimal digits

Double CellEditType.NumericEdit NumericTextBox control with


default two decimal digits

Date-time CellEditType.DateTimeEdit DatePicker control

Methods

Method Parameters Return type Description


Editing Action<IEditingBuild IGridBuilder<T Used to configure the editing
(Action<IEditingBuilder er<T>> > mode.
<T>> editing)

© 2014 Syncfusion. All rights reserved. 257 | Page


Essential Grid for ASP.NET MVC Classic

AllowNew(bool Bool, string IEditingBuilder Used to configure the Add


allowDelete, string <T> New action in the editing
mapperName) mode.
Used to set the mapper name
and enable or disable the Add
New action.

AllowEdit(bool Bool, string IEditingBuilder Used to configure the Edit


allowEdit, string <T> action in the editing mode.
mapperName)
Used to set the mapper name
and to enable or disable the
Edit action.

AllowDelete(bool Bool, string IEditingBuilder Used to configure the Delete


allowDelete, string <T> action in the editing mode.
mapperName)
Used to set the mapperName
and enable or disable the
Delete action

EditMode(GridEditMod GridEditMode IEditingBuilder Used to configure the grid’s


e editMode) <T> editing mode. Set any editing
mode from an enum
collection. Default is Normal.

FormModeEditorTempl String partialview IEditingBuilder Used to set the partial view


ate(string name <T> name in the inline template
editmodeTemplate) form editing mode.

PrimaryKey(Action<IG Action<IGridPrimary IEditingBuilder Used to add primary keys to


ridPrimaryKeyBuilder< KeyBuilder<T>> <T> grid which are used in the
T>> key) editing mode to uniquely
identify the record.

CloseOnEscape(bool Bool IEditingBuilder Used to enable or disable the


enable) <T> ESC key event in cancel
request through the keyboard.

SaveOnEnter(bool Bool IEditingBuilder Used to enable or disable the


enable) <T> ENTER key event to raise the
save request through the
keyboard.

Add(Expression<Func Expression IGridPrimaryK Used to add primary keys to

© 2014 Syncfusion. All rights reserved. 258 | Page


Essential Grid for ASP.NET MVC Classic

<T, object>> eyBuilder<T> the grid.


expression)

ToolBar(Action<IToolB Action<IToolbarbuild IEditingBuilder Used to configure the toolbar


arBuilder> toobar) er> toolbar <T> in the editing mode.

Add(GridToolBarItems GridToolBarItems IToolBarBuilde Used to add a toolbar item to


item) r grid.

Add(GridToolBarItems GridToolBarItems, IToolBarBuilde Used to add a toolbar item


item, string caption) string r with a caption.

EnableToolbar(bool Bool IToolBarBuilde Used to enable or disable the


enable) r toolbar in the grid.

4.7.1 Server Mode


You can work with the editing feature through two ways:
 GridBuilder
 GridPropertiesModel

4.7.1.1 Through GridBuilder


The steps to work with the editing feature through GridBuilder are as follows:
1. Add the MicrosoftMvcValidation.debug.js file in the master page.

[Site.Master]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

© 2014 Syncfusion. All rights reserved. 259 | Page


Essential Grid for ASP.NET MVC Classic

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>

© 2014 Syncfusion. All rights reserved. 260 | Page


Essential Grid for ASP.NET MVC Classic

<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application. Refer to How to>Adding a Model to the Application and
Editing>EditableOrder Class.
3. Create a strongly typed view. Refer to How to>Strongly Typed View.
4. In the view, use the Model property in the Datasource() to bind the data source.

View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");

})
.EnablePaging()
.EnableSorting()
.EnableGrouping()

%>

View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>

© 2014 Syncfusion. All rights reserved. 261 | Page


Essential Grid for ASP.NET MVC Classic

p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");

})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();

5. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete, as displayed below.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify the
controller and action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete action.

})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify the
controller and action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the

© 2014 Syncfusion. All rights reserved. 262 | Page


Essential Grid for ASP.NET MVC Classic

controller and action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete action.

}).Render();

Note: If you want to specify the URL in the AllowEdit property itself means, specify the controller
and the corresponding action name as a URL. If you using the Mappers property then there is no
need to specify the controller name.

6. Grid allows adding new records through grid toolbar items. In this example, the AddNew,
Edit, Delete, Save, and Cancel buttons have been added as toolbar items in the following
code sample.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for Cancel request.
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for insert record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting record.

© 2014 Syncfusion. All rights reserved. 263 | Page


Essential Grid for ASP.NET MVC Classic

.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for Cancel request.
}).Render();

7. Specify the Primary property which uniquely identifies the grid record.
View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add primary key to primary key collections.

})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add primary key to primary key collections.

}).Render();
}

You can also add multiple primary keys. The following code illustrates this:
View[Aspx]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID).Add(p => p.EmployeeID).Add(p => p.CustomerID)); // Add
primary key to primary key collections.

})
%>

© 2014 Syncfusion. All rights reserved. 264 | Page


Essential Grid for ASP.NET MVC Classic

8. Specify the grid editing mode through the EditMode() method.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
specify the edit mode

})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
specify the edit mode

}).Render();
}

9. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.

Controller

/// <summary>
/// Used to insert the record into database and refresh the
grid.
/// </summary>
/// <param name="ord">Editable order</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add is used to insert records in
the data source.
OrderRepository.Add(ord);

// After adding the record in the database, refresh the

© 2014 Syncfusion. All rights reserved. 265 | Page


Essential Grid for ASP.NET MVC Classic

grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to repository action codes in Editing>OrderRepository Class.

10. In the controller, create a method to save changes, as displayed below. In this example, the
repository method Update() is used to update records to the data source.
Controller

/// Used to insert the record into database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order</param>
/// <returns>HtmlActionResult which returns data displayed on
the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records in the data source.
OrderRepository.Update(ord);

// After saving the records to the data source, refresh the


grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

11. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() will delete the record from the data
source.

Controller

/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repoistory action Delete() deletes the given primary
value record from the data source.

© 2014 Syncfusion. All rights reserved. 266 | Page


Essential Grid for ASP.NET MVC Classic

OrderRepository.Delete(OrderID);

// After deleting refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

12. Run the application. The grid will appear as displayed below.

Figure 87: Grid with Toolbar Options for Editing, Inserting, and Deleting

The following screenshot shows the default editing controls such as NumericTextBox for integer
types (namely “Employee ID”), NumericTextbox for decimal types (namely “Freight”), DatePicker
for date-time types (namely “Order Date”).

© 2014 Syncfusion. All rights reserved. 267 | Page


Essential Grid for ASP.NET MVC Classic

Figure 88: Grid with Inline Row Editing

Figure 89: Grid with Inline Row Inserting

© 2014 Syncfusion. All rights reserved. 268 | Page


Essential Grid for ASP.NET MVC Classic

Figure 90: Grid after Deletion of Row with OrderID 10002

4.7.1.1.1 Grid EditMode Configuration

 Essential Grid provides three modes for editing. To set the edit form mode of editing, use
the EditMode() method.

View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineForm);

})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineForm);

© 2014 Syncfusion. All rights reserved. 269 | Page


Essential Grid for ASP.NET MVC Classic

}).Render();
}

If you configure the edit mode as InlineForm, the grid will appear in the editing mode displayed
below.

Figure 91: Grid with Inline Form Editing

© 2014 Syncfusion. All rights reserved. 270 | Page


Essential Grid for ASP.NET MVC Classic

Figure 92: Grid with Inline Form Insert Mode

1. If you want to use the TemplateForm mode, follow the steps displayed below.

 Create the template in partial view, as displayed below.

View [ASCX]

<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.OrderID) %>

© 2014 Syncfusion. All rights reserved. 271 | Page


Essential Grid for ASP.NET MVC Classic

</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.OrderID) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.CustomerID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.CustomerID)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.EmployeeID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.EmployeeID)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipName) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipName) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName) %>
</div>

© 2014 Syncfusion. All rights reserved. 272 | Page


Essential Grid for ASP.NET MVC Classic

</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipAddress) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipAddress)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipCity) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipCity) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipRegion) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipRegion)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipCountry) %>
</div>

© 2014 Syncfusion. All rights reserved. 273 | Page


Essential Grid for ASP.NET MVC Classic

<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipCountry)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.Freight) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.Freight) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.OrderDate) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.OrderDate,
String.Format("{0:g}", Model.OrderDate)) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>

View [Razor]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)

© 2014 Syncfusion. All rights reserved. 274 | Page


Essential Grid for ASP.NET MVC Classic

</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>

© 2014 Syncfusion. All rights reserved. 275 | Page


Essential Grid for ASP.NET MVC Classic

model.ShipAddress)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)

© 2014 Syncfusion. All rights reserved. 276 | Page


Essential Grid for ASP.NET MVC Classic

</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>

model.Freight)

</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>

Note: Don’t specify the form in the template. The <fieldset> tag is required to surround the
template input fields, otherwise the buttons will not be displayed by the dialog.
 Configure the GridEditMode as TemplateForm and specify the partial view which
contains the templates.
View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Editing( edit=>{

edit.EditMode(GridEditMode.InlineTemplateForm);

edit.FormModeEditorTemplate("OrderEditorTemplate");//
Specify the partial view page which contains the
templates.
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")

© 2014 Syncfusion. All rights reserved. 277 | Page


Essential Grid for ASP.NET MVC Classic

.Editing( edit=>{

edit.EditMode(GridEditMode.InlineTemplateForm);

edit.FormModeEditorTemplate("OrderEditorTemplate");//
Specify the partial view page which contains the
templates.
}).Render();
}

 In the InlineTemplateForm mode, you should handle the Insert and Edit actions. To
achieve this, check the RequestType property from PagingParams. If the request type
is either BeginEdit or BeginAddNew, render the template by using the PartialView()
method as displayed below.

/// <summary>
/// Paging/editing Request is mapped to this
method. This method invokes the HtmlActionResult
/// from the grid. Required response is
generated.
/// </summary>
/// <param name="args">Contains paging
properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed
on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args
,int? OrderID)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
// Check if the current request is edit
request and edit mode is Template form mode. Then call
the PartialView() to render the template.
if (currentRequest == RequestType.BeginEdit)
{
EditableOrder ord =
(EditableOrder)OrderRepository.Select(OrderID);
return
PartialView("OrderEditorTemplate", ord);
}
else if (currentRequest ==
RequestType.BeginAddNew)
{
// Check if the current request is add
new request and edit mode is Template form mode then
call the Partialview() to render the template.
return

© 2014 Syncfusion. All rights reserved. 278 | Page


Essential Grid for ASP.NET MVC Classic

PartialView("OrderEditorTemplate", new EditableOrder());


}
else
{
IEnumerable data =
OrderRepository.GetAllRecords();
return
data.GridActions<EditableOrder>();
}
}

If you configure the edit mode as TemplateForm, the grid will appear in the editing mode as
displayed below.

Figure 93: Grid with Inline Form Editing

© 2014 Syncfusion. All rights reserved. 279 | Page


Essential Grid for ASP.NET MVC Classic

Figure 94: Grid with Inline Form Inserting

4.7.1.1.2 Disable Editing in Specified Columns

Essential Grid provides support for restricting the editing operations in a column. This can be
done by setting the AllowEditing property of particular columns to False.

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the AllowEditing property of a particular column to False.
View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")

© 2014 Syncfusion. All rights reserved. 280 | Page


Essential Grid for ASP.NET MVC Classic

.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID").AllowEditing(false);
column.Add(p => p.ShipCountry).HeaderText("Ship
Country").AllowEditing(false);
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");

})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID").AllowEditing(false);
column.Add(p => p.ShipCountry).HeaderText("Ship
Country").AllowEditing(false);
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");

})

.Render();
}

Note: In the code samples, the “Customer ID” and “Ship Country” columns cannot be editable.
5. Render the view.

Controller

public ActionResult Index()


{
var data = new NorthwindDataContext().Orders;
return View(data);
}

6. Run the application and edit the particular record. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 281 | Page


Essential Grid for ASP.NET MVC Classic

Figure 95: Grid Columns with Editing Disabled

4.7.1.2 Through GridPropertiesModel

The steps to work with the editing feature through GridPropertiesModel are as follows.
1. Add the MicrosoftMvcValidation.debug.js file in the master page.
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

© 2014 Syncfusion. All rights reserved. 282 | Page


Essential Grid for ASP.NET MVC Classic

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application. Refer to How to>Adding a Model to the Application and
Editing>EditableOrder Class.
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel
", column=> {

© 2014 Syncfusion. All rights reserved. 283 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p => p.OrderID).HeaderText("Order ID");


column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column=> {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
}))

5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};

ViewData["GridModel"] = model; // Pass the model from


controller to view using ViewData.

6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AllowNew, AllowEdit, and AllowDelete as displayed below.
Controller

//Create object to grid editing and enable edit, addnew, and

© 2014 Syncfusion. All rights reserved. 284 | Page


Essential Grid for ASP.NET MVC Classic

delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true,
AllowDelete = true, AllowNew = true };

//Set the action mappers for insert,delete and save


actions.
edit.DeleteMapper = "DeleteOrder";
edit.InsertMapper = "AddOrder";
edit.GridSaveMapper = "OrderSave";

7. Specify the grid editing mode through the EditMode property.

Controller

//Set the Edit mode.


edit.EditMode = GridEditMode.Normal;

8. Specify the primary property, which uniquely identifies the grid record.
Controller

// Add the primarykey value to identify the record uniquely.


edit.PrimaryKey = new List<string>() { "OrderID" };

9. Add the Edit setting to the model.


Controller

// Add the edit setting to model.


model.Editing = edit;

Essential Grid allows adding new records through grid toolbar items. In this example, AddNew,
Edit, Delete, Save, and Cancel buttons have been added as toolbar items in the code sample
displayed below.
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();

toolbar.Enable = true;

// Add the add new, edit, delete, save, cancel button in


toolbar.

toolbar.Items.Add(new ToolbarOptions() { ItemType=


GridToolBarItems.AddNew});
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });

toolbar.Items.Add(new ToolbarOptions() { ItemType =

© 2014 Syncfusion. All rights reserved. 285 | Page


Essential Grid for ASP.NET MVC Classic

GridToolBarItems.Delete });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Update });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Cancel });

model.ToolBar = toolbar;

Note: In our earlier versions, toolbar item collection is of type Dictionary<GridToolBarItems key,
string value>. With the inclusion of custom toolbar item support, we can’t add multiple custom
items. The key will be the same (GridToolBarItems.Custom) for all custom items and so we have
modified the toolbar item collection type as List<ToolbarOptions>.

10. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.
Controller

/// <summary>
/// Used to insert the record into database and refresh the
grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add is used to insert records in
the data source.
OrderRepository.Add(ord);

// After adding the record into the database, refresh the


grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes in Editing > OrderRepository Class.
11. In the controller, create a method to save changes as displayed below. In this example, the
repository method Update() is used to update records to the data source.
Controller

© 2014 Syncfusion. All rights reserved. 286 | Page


Essential Grid for ASP.NET MVC Classic

/// Used to insert the record into database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records in the data source.
OrderRepository.Update(ord);

// After saving the records in the data source refresh the


grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

12. In the controller, create a method to delete records from the database as displayed below.
In this example, the repository action Delete() will delete the record from the data source.
Controller
/// <summary>
/// Used for deleting records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repoistory action Delete()deletes the given primary
value record from the data source.
OrderRepository.Delete(OrderID);

// After deleting, refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

13. Run the application. The grid will appear as displayed below.

© 2014 Syncfusion. All rights reserved. 287 | Page


Essential Grid for ASP.NET MVC Classic

Figure 96: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

© 2014 Syncfusion. All rights reserved. 288 | Page


Essential Grid for ASP.NET MVC Classic

Figure 97: Grid with Inline Row Editing

Figure 98: Grid with Inline Row Inserting

Figure 99: OrderID 10251 Deleted from Grid

© 2014 Syncfusion. All rights reserved. 289 | Page


Essential Grid for ASP.NET MVC Classic

4.7.1.2.1 Grid EditMode Configuration

Essential Grid provides three modes for editing. To set the InlineForm edit mode, use the
EditMode property.

Controller
//Create object to grid editing and enable edit, addnew, and
delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true,
AllowDelete = true, AllowNew = true };
//Set the Edit mode.
edit.EditMode = GridEditMode.InlineForm;

If you configure the edit mode as EditForm, the grid will appear in the editing mode as displayed
below.

© 2014 Syncfusion. All rights reserved. 290 | Page


Essential Grid for ASP.NET MVC Classic

Figure 100: Grid with Inline Form Editing

© 2014 Syncfusion. All rights reserved. 291 | Page


Essential Grid for ASP.NET MVC Classic

Figure 101: Grid with Inline Form Insert Mode

If you want to use the TemplateForm mode, follow the steps displayed below:
1. Create the template in partial view as displayed below.
View [ASCX]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.OrderID) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model

© 2014 Syncfusion. All rights reserved. 292 | Page


Essential Grid for ASP.NET MVC Classic

=> model.OrderID) %>


<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.CustomerID) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.CustomerID) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.EmployeeID) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.EmployeeID) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.ShipName) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.ShipName) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">

© 2014 Syncfusion. All rights reserved. 293 | Page


Essential Grid for ASP.NET MVC Classic

<%= Html.Syncfusion().LabelFor(model =>


model.ShipAddress) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.ShipAddress) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.ShipCity) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.ShipCity) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.ShipRegion) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.ShipRegion) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.ShipCountry) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.ShipCountry) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry) %>
</div>

© 2014 Syncfusion. All rights reserved. 294 | Page


Essential Grid for ASP.NET MVC Classic

</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.Freight) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.Freight) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model =>
model.OrderDate) %>
</div>
<div class="editor-field">
<%= Html.Syncfusion().TextBoxFor(model
=> model.OrderDate, String.Format("{0:g}",
Model.OrderDate)) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>

View [Razor]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>

© 2014 Syncfusion. All rights reserved. 295 | Page


Essential Grid for ASP.NET MVC Classic

<div class="celldiv" style="height: auto">


<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipAddress)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>

© 2014 Syncfusion. All rights reserved. 296 | Page


Essential Grid for ASP.NET MVC Classic

</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>

model.Freight)

</div>

© 2014 Syncfusion. All rights reserved. 297 | Page


Essential Grid for ASP.NET MVC Classic

</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>

Note: Don’t specify the form in the template. The <fieldset> tag is required to surround the
template input fields else the buttons will not be displayed by the dialog.

2. Configure the GridMode as TemplateFormMode and specify the partial view which
contains the templates.

Controller
//Create object to grid editing and enable edit,
addnew and delete actions.
GridEditing edit = new GridEditing() {
AllowEdit = true, AllowDelete = true, AllowNew = true };

//Set the Edit mode.


edit.EditMode =
GridEditMode.InlineTemplateForm;
edit.FormModeEditorTemplate =
"OrderEditorTemplate”;

3. In the InlineTemplateForm mode, you should handle the Insert action Edit actions. To
achieve this, check the RequestType property from PagingParams. If the request type
is either BeginEdit or BeginAddNew, then render the template by using the
PartialView() method as displayed below.

Controller
/// <summary>
/// The paging/editing request is mapped to this
method. This method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>

© 2014 Syncfusion. All rights reserved. 298 | Page


Essential Grid for ASP.NET MVC Classic

/// <param name="args">Contains paging properties.


</param>
/// <returns>
/// HtmlActionResult returns the data displayed on
the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args ,int?
OrderID)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
// Check if the current request is edit request
and edit mode is Template form mode then call the
Partialview() to renders the template.
if (currentRequest == RequestType.BeginEdit)
{
EditableOrder ord =
(EditableOrder)OrderRepository.Select(OrderID);
return PartialView("OrderEditorTemplate",
ord);
}
else if (currentRequest ==
RequestType.BeginAddNew)
{
// Check if the current request is add new
request and edit mode is Template form mode then call the
Partialview() to render the template.
return PartialView("OrderEditorTemplate",
new EditableOrder());
}
else
{
IEnumerable data =
OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
}

If you configure the edit mode as TemplateForm, the grid will appear in the editing mode as
displayed below.

© 2014 Syncfusion. All rights reserved. 299 | Page


Essential Grid for ASP.NET MVC Classic

Figure 102: Grid with Inline Form Editing

© 2014 Syncfusion. All rights reserved. 300 | Page


Essential Grid for ASP.NET MVC Classic

Figure 103: Grid with Inline Form Inserting Action

4.7.2 JSON Mode

4.7.2.1 Through GridBuilder


The steps to work with the editing feature through GridBuilder are as follows:
1. Add the MicrosoftMvcValidation.debug.js file in the master page.

[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

© 2014 Syncfusion. All rights reserved. 301 | Page


Essential Grid for ASP.NET MVC Classic

</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">

© 2014 Syncfusion. All rights reserved. 302 | Page


Essential Grid for ASP.NET MVC Classic

. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application (Refer to How to>Adding a Model to the Application).
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Create the Grid control in the view and configure its properties.
5. Set the JSON action mode using the ActionMode method.
6. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and Allow Delete as displayed below.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify the
action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the
action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the action method which will perform the delete action.
})
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>

© 2014 Syncfusion. All rights reserved. 303 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify the
action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the
action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the action method which will perform the delete action.
})
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}

Note: If you want to specify the URL in the AllowEdit property itself, specify the controller and
the corresponding action name as a URL. If you are using the Mappers property then there is no
need to specify the controller name.

7. Essential Grid allows adding new records through toolbar items. In this example, AddNew,
Edit, Delete, Save, and Cancel buttons have been added as toolbar items as displayed
below.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for Insert record.
.Add(GridToolBarItems.Edit)// Toolbar
item for Editing record.
.Add(GridToolBarItems.Delete)// Toolbar
item for Deleting record.
.Add(GridToolBarItems.Update)// Toolbar
item for save changes.

© 2014 Syncfusion. All rights reserved. 304 | Page


Essential Grid for ASP.NET MVC Classic

.Add(GridToolBarItems.Cancel);// Toolbar
item for Cancel request.
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for Insert record.
.Add(GridToolBarItems.Edit)// Toolbar
item for Editing record.
.Add(GridToolBarItems.Delete)// Toolbar
item for Deleting record.
.Add(GridToolBarItems.Update)// Toolbar
item for save changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for Cancel request.
}).Render();
}

8. Specify the Primary property which uniquely identifies the grid record.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add
the primary key to primary key collections.
})
%>

© 2014 Syncfusion. All rights reserved. 305 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add
the primary key to primary key collections.
}).Render();
}

9. Specify the GridEditing mode through the EditMode() method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add
primary key to primary key collections.
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add
primary key to primary key collections.
}).Render();
}

10. Render the view.

Controller

public ActionResult Index()


{
return View();
}

11. In order to work with editing actions, create a Post method for Index actions and bind the
data source to the grid as given in the following code.

© 2014 Syncfusion. All rights reserved. 306 | Page


Essential Grid for ASP.NET MVC Classic

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

12. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add is used to insert records into the
datasource.
OrderRepository.Add(ord);

// After adding the record into database refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

13. In the controller, create a method to save changes as displayed below. In this example, the
repository method Update() is used to update records in the data source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the records
into the datasource.
OrderRepository.Update(ord);

// After saving records into the datasource refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

14. In the controller, create a method to delete records from the database as displayed below.
In this example, the repository action Delete() will delete the record from the data source.
Controller

[AcceptVerbs(HttpVerbs.Post)]

© 2014 Syncfusion. All rights reserved. 307 | Page


Essential Grid for ASP.NET MVC Classic

public ActionResult DeleteOrder(int OrderID)


{
// Repository action Delete(), deletes the given primary value
record from the datasource.
OrderRepository.Delete(OrderID);

// After deleting, refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

15. Run the application. The grid will appear as shown below.

Figure 104: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

© 2014 Syncfusion. All rights reserved. 308 | Page


Essential Grid for ASP.NET MVC Classic

Figure 105: Grid with Inline Row Editing

Figure 106: Grid with Inline Row Inserting

© 2014 Syncfusion. All rights reserved. 309 | Page


Essential Grid for ASP.NET MVC Classic

Figure 107: Grid after Deletion of Row with OrderID 10002

4.7.2.1.1 Grid EditMode Configuration

 Essential Grid provides three modes for editing. To change the EditForm mode in editing,
use the EditMode() method.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineForm);

})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.InlineForm);

© 2014 Syncfusion. All rights reserved. 310 | Page


Essential Grid for ASP.NET MVC Classic

}).Render();
}

After configuring the edit mode as InlineForm, the grid will appear in the editing mode as
displayed below.

Figure 108: Grid with Inline Form Editing

© 2014 Syncfusion. All rights reserved. 311 | Page


Essential Grid for ASP.NET MVC Classic

Figure 109: Grid with Inline Form Insert Mode

To use the Templateform editing mode, follow the steps displayed below.
Create the template in partial view, as shown in the following code sample.
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.OrderID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.OrderID) %>
<%= Html. ValidationMessageFor(model
=> model.OrderID) %>

© 2014 Syncfusion. All rights reserved. 312 | Page


Essential Grid for ASP.NET MVC Classic

</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.CustomerID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.CustomerID) %>
<%= Html. ValidationMessageFor(model
=> model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.EmployeeID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.EmployeeID) %>
<%= Html. ValidationMessageFor(model
=> model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipName) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipName) %>
<%= Html. ValidationMessageFor(model
=> model.ShipName) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipAddress) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipAddress) %>
<%= Html. ValidationMessageFor(model
=> model.ShipAddress) %>
</div>
</div>

© 2014 Syncfusion. All rights reserved. 313 | Page


Essential Grid for ASP.NET MVC Classic

<div class="celldiv" style="height: auto">


<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipCity) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipCity) %>
<%= Html. ValidationMessageFor(model
=> model.ShipCity) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipRegion) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipRegion) %>
<%= Html. ValidationMessageFor(model
=> model.ShipRegion) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipCountry) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipCountry) %>
<%= Html. ValidationMessageFor(model
=> model.ShipCountry) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.Freight) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.Freight) %>
<%= Html. ValidationMessageFor(model
=> model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">

© 2014 Syncfusion. All rights reserved. 314 | Page


Essential Grid for ASP.NET MVC Classic

<%= Html. LabelFor(model =>


model.OrderDate) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.OrderDate, String.Format("{0:g}",
Model.OrderDate)) %>
<%= Html. ValidationMessageFor(model
=> model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>

View [Razor]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">

© 2014 Syncfusion. All rights reserved. 315 | Page


Essential Grid for ASP.NET MVC Classic

@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipAddress)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">

© 2014 Syncfusion. All rights reserved. 316 | Page


Essential Grid for ASP.NET MVC Classic

@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>

model.Freight)

</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>

© 2014 Syncfusion. All rights reserved. 317 | Page


Essential Grid for ASP.NET MVC Classic

Note: Don’t specify the form in the template. The <fieldset> tag is required to surround the
template input fields, otherwise the buttons will not be displayed by the dialog.
Configure the GridMode as TemplateFormMode and specify the partial view which contains the
templates.
View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.I
nlineTemplateForm);
edit.FormModeEditorTemplate(
"OrderEditorTemplate");// Specify the partial view page
which contains the
templates.
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Editing( edit=>{
edit.EditMode(GridEditMode.I
nlineTemplateForm);
edit.FormModeEditorTemplate(
"OrderEditorTemplate");// Specify the partial view page
which contains the
templates.
}).Render();

© 2014 Syncfusion. All rights reserved. 318 | Page


Essential Grid for ASP.NET MVC Classic

Figure 110: Grid with Inline Form Template Mode Editing

© 2014 Syncfusion. All rights reserved. 319 | Page


Essential Grid for ASP.NET MVC Classic

Figure 111: Grid with Inline Form Template Mode Inserting

4.7.2.2 Through GridPropertiesModel


The steps to work with the editing feature through the GridPropertiesModel are as follows:
1. Add the MicrosoftMvcValidation.debug.js file in the master page.

[Site.Master]

<head runat="server">

<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"


/></title>

………

<script src="<%=

© 2014 Syncfusion. All rights reserved. 320 | Page


Essential Grid for ASP.NET MVC Classic

Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

© 2014 Syncfusion. All rights reserved. 321 | Page


Essential Grid for ASP.NET MVC Classic

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application. Refer to How to>Adding a Model to the Application
19. and Editing>EditableOrder Class.
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file, to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel
", column=> {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
column=> {
column.Add(p => p.OrderID).HeaderText("Order ID");

column.Add(p => p.EmployeeID).HeaderText("Employee ID");

column.Add(p => p.CustomerID).HeaderText("Customer ID");

column.Add(p => p.ShipCountry).HeaderText("Ship Country");

column.Add(p => p.OrderDate).HeaderText("Order


Date").Format("{OrderDate:MM/dd/yyyy}");

column.Add(p => p.Freight).HeaderText("Freight");

}))

© 2014 Syncfusion. All rights reserved. 322 | Page


Essential Grid for ASP.NET MVC Classic

5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.

Controller
GridPropertiesModel<EditableOrder> model = new
GridPropertiesModel<EditableOrder>()
{
ActionMode = ActionMode.JSON,
Caption = "Orders",
AutoFormat=Skins.Sandune
};
ViewData["GridModel"] = model; // Pass the model from
controller to view using ViewData.

6. Enable editing by using the Editing property in the GridPropertiesModel, and configure
the editing properties such as AllowNew, AllowEdit, and AllowDelete as displayed below.
Controller

// Create an object for grid editing and enable the edit, addnew
and delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true,
AllowDelete = true, AllowNew = true };

// Set the action mappers for insert, delete and save


actions.
edit.DeleteMapper = "DeleteOrder";
edit.InsertMapper = "AddOrder";
edit.GridSaveMapper = "OrderSave";

7. Specify the grid editing mode through the EditMode property.


Controller

// Set the Edit mode.

edit.EditMode = GridEditMode.Normal;
20.
8. Specify the primary property which uniquely identifies the grid record.
Controller

// Add the primarykey value to identify the record uniquely.

edit.PrimaryKey = new List<string>() { "OrderID" };


21.
9. Add the Edit setting to the model.
Controller

// Add the edit setting to model.

model.Editing = edit;

© 2014 Syncfusion. All rights reserved. 323 | Page


Essential Grid for ASP.NET MVC Classic

22.
10. Essential Grid allows adding new records through grid toolbar items. In this example, the
AddNew, Edit, Delete, Save, and Cancel buttons have been added as toolbar items.
23.
Controller

// Configure the toolbar.


ToolbarSettings toolbar = new ToolbarSettings();

toolbar.Enable = true;

// Add the Add New, Edit, Delete, Save, and Cancel buttons
to the toolbar.

toolbar.Items.Add(new ToolbarOptions() { ItemType=


GridToolBarItems.AddNew});
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Delete });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Update });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Cancel });

model.ToolBar = toolbar;

Note: In our earlier versions, the toolbar item collection type is Dictionary<GridToolBarItems
key, string value>. With the inclusion of custom toolbar item support, we can’t add multiple custom
items. The key will be the same (GridToolBarItems.Custom) for all custom items and so we have
modified the toolbar item collection type as List<ToolbarOptions>.
24.
11. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.

Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// The repository action method Add is used to insert records
into the datasource.
OrderRepository.Add(ord);

// Refresh the grid after adding the record into the


database.
var data = OrderRepository.GetAllRecords();

© 2014 Syncfusion. All rights reserved. 324 | Page


Essential Grid for ASP.NET MVC Classic

return data.GridJSONActions<EditableOrder>();
}

Note: Refer to repository action codes in Editing>OrderRepository Class .


12. In the controller, create a method to save changes as displayed below. In this example, the
repository method Update() is used to update records to the data source.
25.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records into datasource.
OrderRepository.Update(ord);

// Refresh the grid after saving the records into the


datasource.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

13. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() is used to delete the record from the
data source.
26.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the datasource.
OrderRepository.Delete(OrderID);

// Refresh the grid, after deleting.


var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

14. In order to work with editing actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.
27.

© 2014 Syncfusion. All rights reserved. 325 | Page


Essential Grid for ASP.NET MVC Classic

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

15. Run the application. The grid will appear as shown in the following screenshots:

Figure 112: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

© 2014 Syncfusion. All rights reserved. 326 | Page


Essential Grid for ASP.NET MVC Classic

Figure 113: Grid with Inline Row Editing

Figure 114: Grid with Inline Row Inserting

© 2014 Syncfusion. All rights reserved. 327 | Page


Essential Grid for ASP.NET MVC Classic

Figure 115: Grid after Deletion of Row with OrderID 10002

4.7.2.2.1 Grid EditMode Configuration


Essential Grid provides three modes of editing. To set the EditForm mode of editing, use the
EditMode() method.
Controller

// Create object to grid editing and enable the edit, addnew, and
delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true,
AllowDelete = true, AllowNew = true };
// Set the Edit mode.
edit.EditMode = GridEditMode.InlineForm;

If the edit mode is configured as InlineForm, the grid will appear as displayed below.

© 2014 Syncfusion. All rights reserved. 328 | Page


Essential Grid for ASP.NET MVC Classic

Figure 116: Grid with Inline Form Editing

© 2014 Syncfusion. All rights reserved. 329 | Page


Essential Grid for ASP.NET MVC Classic

Figure 117: Grid with Inline Form Insert Mode

To use the TemplateForm mode, use the following steps:


1. Create the template in partial view as displayed below.
<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.OrderID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.OrderID) %>
<%= Html. ValidationMessageFor(model
=> model.OrderID) %>
</div>

© 2014 Syncfusion. All rights reserved. 330 | Page


Essential Grid for ASP.NET MVC Classic

</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.CustomerID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.CustomerID) %>
<%= Html. ValidationMessageFor(model
=> model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.EmployeeID) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.EmployeeID) %>
<%= Html. ValidationMessageFor(model
=> model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipName) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipName) %>
<%= Html. ValidationMessageFor(model
=> model.ShipName) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipAddress) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipAddress) %>
<%= Html. ValidationMessageFor(model
=> model.ShipAddress) %>
</div>
</div>
<div class="celldiv" style="height: auto">

© 2014 Syncfusion. All rights reserved. 331 | Page


Essential Grid for ASP.NET MVC Classic

<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipCity) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipCity) %>
<%= Html. ValidationMessageFor(model
=> model.ShipCity) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipRegion) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipRegion) %>
<%= Html. ValidationMessageFor(model
=> model.ShipRegion) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.ShipCountry) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.ShipCountry) %>
<%= Html. ValidationMessageFor(model
=> model.ShipCountry) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>
model.Freight) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.Freight) %>
<%= Html. ValidationMessageFor(model
=> model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html. LabelFor(model =>

© 2014 Syncfusion. All rights reserved. 332 | Page


Essential Grid for ASP.NET MVC Classic

model.OrderDate) %>
</div>
<div class="editor-field">
<%= Html. TextBoxFor(model =>
model.OrderDate, String.Format("{0:g}",
Model.OrderDate)) %>
<%= Html. ValidationMessageFor(model
=> model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>

View [Razor]

<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">

© 2014 Syncfusion. All rights reserved. 333 | Page


Essential Grid for ASP.NET MVC Classic

@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipAddress)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">

© 2014 Syncfusion. All rights reserved. 334 | Page


Essential Grid for ASP.NET MVC Classic

@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>

model.Freight)

</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>

© 2014 Syncfusion. All rights reserved. 335 | Page


Essential Grid for ASP.NET MVC Classic

Note: Don’t specify the form in the template. And the <fieldset> tag is required to surround the
template input fields else the buttons will not be displayed by the dialog.
2. Configure the GridMode as TemplateFormMode and specify the partial view which
contains the templates.

Controller
// Create an object to grid editing and enable the
edit, addnew, and delete actions.
GridEditing edit = new GridEditing() {
AllowEdit = true, AllowDelete = true, AllowNew = true };

// Set the Edit mode.


edit.EditMode =
GridEditMode.InlineTemplateForm;
edit.FormModeEditorTemplate =
"OrderEditorTemplate”;

Figure 118: Grid with Inline Form Template Mode Editing

© 2014 Syncfusion. All rights reserved. 336 | Page


Essential Grid for ASP.NET MVC Classic

Figure 119: Grid with Inline Form Template Mode Inserting

Events
Event Description Arguments Type Reference links

OnRecordAdd This event occurs when String handler


Client-Side N/A
New a new record is added.

This event occurs when String handler


OnRecordEdit Client-Side N/A
a record is edited.

Using Client-Side Events

© 2014 Syncfusion. All rights reserved. 337 | Page


Essential Grid for ASP.NET MVC Classic

The client-side events are used in ASPX as shown in the following code table in server mode
through GridBuilder.
View[ASPX]

<%=Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.Editing( edit=>{

edit.AllowEdit(true,"Home/OrderSave")// Specify the action method


which will perform the update action.

.AllowNew(true,"Home/AddOrder") //Specify the action method which


will perform the insert action.
})
.ClientSideEvents(eve =>
{
eve.OnRecordAddNew
("OnRecordAddNew");
eve.OnRecordEdit ("OnRecordEdit");
})
%>

For Razor, use the code shown below in the following table in server mode through GridBuilder.

View[cshtml]
@{
Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.Editing( edit=>{

edit.AllowEdit(true,"Home/OrderSave") // Specify the action


method which will perform the update action.

.AllowNew(true,"Home/AddOrder") //Specify the action method which

© 2014 Syncfusion. All rights reserved. 338 | Page


Essential Grid for ASP.NET MVC Classic

will perform the insert action.


})
.ClientSideEvents(eve =>
{
eve.OnRecordAddNew("OnRecordAddNew");
eve.OnRecordEdit("OnRecordEdit");
})
.Render();
}

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > JSON Mode

4.7.3 Adding Editing-Rows


Editing rows allow you to create new records by entering data directly into a row. This feature
allows you to create a new record by adding an editing row to the bottom of a grid. To do this, use
the AddNewRowPosition property.

Figure 120: New Editing-Row at Bottom of Grid

4.7.3.1 Properties
Property Description Type of Value it Reference

© 2014 Syncfusion. All rights reserved. 339 | Page


Essential Grid for ASP.NET MVC Classic

property accepts links


AddNewRowPosition Specifies RowPosition Default N/A
whether the
enum RowPosition.Top
new editing row
is added to the
top or bottom
of a grid.

4.7.3.2 Configuring an editing-row


A grid can be rendered in two ways:

 Through the GridBuilder.


 Through the GridPropertiesModel.

4.7.3.2.1 Through GridBuilder


1. Use the following steps to enable a grid to add a new editing row to the bottom using the
Grid Builder:Add the MicrosoftMvcValidation.debug.js file in the master page.
[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

© 2014 Syncfusion. All rights reserved. 340 | Page


Essential Grid for ASP.NET MVC Classic

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application. (Refer to How to > Adding a Model to the Application and
Editing > EditableOrder Class.)
3. Create a strongly typed view. (Refer to How to > Strongly Typed View.)
4. In the view, use the Model property in Datasource() to bind the data source.
5. Enable editing by using the Editing method and configure the editing properties:
AllowNew, AllowEdit, and AllowDelete.
6. Essential Grid allows adding new records through grid toolbar items. (Refer to Concepts
and Features > Editing).
7. Specify the primary property that uniquely identifies the grid record. Specify the GridEditing
mode using the EditMode() method. (Refer to Concepts and Features > Editing).
8. Specify the new row position using the AddNewRowPosition property.
View [ASPX]

© 2014 Syncfusion. All rights reserved. 341 | Page


Essential Grid for ASP.NET MVC Classic

<%=Html.Syncfusion().Grid< EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
columns.Add(p => p.ShipCity).HeaderText("Ship City");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.ShipAddress).HeaderText("Ship Address");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
columns.Add(p => p.Freight);
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AddNewRowPosition(RowPosition.Bottom)
.AllowNew(true)
.AllowDelete(true)
.EditMode(GridEditMode.Normal)
.PrimaryKey(key => key.Add(p => p.OrderID));
})
.EnablePaging()
.EnableSorting()
.EnableFiltering()
%>

View [cshtml]

@{ Html.Syncfusion().Grid< EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
columns.Add(p => p.ShipCity).HeaderText("Ship City");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.ShipAddress).HeaderText("Ship Address");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
columns.Add(p => p.Freight);
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AddNewRowPosition(RowPosition.Bottom)
.AllowNew(true)
.AllowDelete(true)
.EditMode(GridEditMode.Normal)
.PrimaryKey(key => key.Add(p => p.OrderID));

© 2014 Syncfusion. All rights reserved. 342 | Page


Essential Grid for ASP.NET MVC Classic

})
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.Render();
}

9. In the controller, create a method to add new records to the grid, as displayed below. In this
example, the repository method Add() is being created to insert records in the database.
Refer to the repository action method shown below.
Controller

/// <summary>
/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record to the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

10. In the controller, create a method to save changes. In this example, the repository method
Update() is used to update records to the data source.

Controller

/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// The repository action method Update is used to update the records to
the data source.
OrderRepository.Update(ord);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

© 2014 Syncfusion. All rights reserved. 343 | Page


Essential Grid for ASP.NET MVC Classic

11. In the controller, create a method to delete the records from the database. In this example,
the repository action Delete() will delete the record from the data source.

Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary-value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

12. Run the application. The grid will appear as shown below.

Figure 121: Grid with Toolbar Options for Editing, Inserting, and Deleting

The following image shows the new edit-row position when the Add New Record button, located
in the toolbar, is clicked.

© 2014 Syncfusion. All rights reserved. 344 | Page


Essential Grid for ASP.NET MVC Classic

Figure 122: Adding a New Editing-Row at the Bottom of a Grid

4.7.3.2.2 Through GridPropertiesModel


Use the following steps to enable a grid to add a new editing-row at its bottom using the Grid
Properties Model:
1. Add the MicrosoftMvcValidation.debug.js file in the master page.
[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

© 2014 Syncfusion. All rights reserved. 345 | Page


Essential Grid for ASP.NET MVC Classic

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application. (Refer to How to > Adding a Model to the
Application and Editing > EditableOrder Class.)
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file to create the Grid control in the
view.

View [ASPX]

© 2014 Syncfusion. All rights reserved. 346 | Page


Essential Grid for ASP.NET MVC Classic

<%=Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
columns.Add(p => p.ShipCity).HeaderText("Ship City");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.ShipAddress).HeaderText("Ship Address");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
columns.Add(p => p.Freight);
})
%>

View [cshtml]

@( Html.Syncfusion().Grid<EditableOrder>("Orders_Grid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
columns.Add(p => p.ShipCity).HeaderText("Ship City");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.ShipAddress).HeaderText("Ship Address");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
columns.Add(p => p.Freight);
})
)

5. Create GridPropertiesModel in the Index action and assign the grid properties
in the model.

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};

ViewData["GridModel"] = model; // Pass the model from the


controller to the view using ViewData

6. Enable editing by using the Editing property in the GridPropertiesModel and


configure the editing properties: AllowNew, AllowEdit, and AllowDelete.
7. Specify the grid’s editing mode using the EditMode property.

© 2014 Syncfusion. All rights reserved. 347 | Page


Essential Grid for ASP.NET MVC Classic

8. Specify the Primary property, which uniquely identifies the grid record.
9. Add the edit setting to the model. Essential Grid allows new records to be edited
by using toolbar items. (Refer to Concepts and Features > Editing.)
10. Specify the position of the new editing-row by using the AddNewRowPosition
property.

Controller

// Specify the position of the new editing-row.


edit.AddNewRowPosition = RowPosition.Bottom;

11. Add the edit object to the model.

Controller

// Add the edit object to the model.


model.Editing = edit;

12. Essential Grid allows new records to be added through toolbar items. In the
following example, AddNew, Edit, Delete, Save, and Cancel buttons have been
added as toolbar items.

Controller

// Configure the toolbar.


ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
// Add the AddNew, Edit, Delete, Save, and Cancel buttons to the
toolbar.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.AddNew});
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Delete });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Update });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Cancel });
model.ToolBar = toolbar;

13. In the controller, create a method to add new records to the grid. In this example,
the repository method Add() has been created to insert records in the database.
Note the repository action method shown in the following code.

Controller

/// <summary>

© 2014 Syncfusion. All rights reserved. 348 | Page


Essential Grid for ASP.NET MVC Classic

/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// The repository action method Add() is used to insert records in the
data source.
OrderRepository.Add(ord);
// After adding the record to the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

14. In the controller, create a method to save changes. In this example, the
repository method Update() is used to update records to the data source:

Controller

/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// The repository action method Update is used to update the records to
the data source.
OrderRepository.Update(ord);
//After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

15. In the controller, create a method to delete the records from the database. In this
example, the repository action Delete() will delete the record from the data
source.
Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]

© 2014 Syncfusion. All rights reserved. 349 | Page


Essential Grid for ASP.NET MVC Classic

public ActionResult DeleteOrder(int OrderID)


{
// The repository action Delete() deletes the given primary-value
record from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

16. Run the application. The grid will appear as shown in the following image.

Figure 123: Grid with Toolbar Options for Editing, Inserting, and Deleting

The following image shows the new edit-row position when the Add New Record button, located
in the toolbar, is clicked.

Figure 124: Adding a New Edit-Row to the Bottom of a Grid

© 2014 Syncfusion. All rights reserved. 350 | Page


Essential Grid for ASP.NET MVC Classic

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Server Mode/JSON Mode

4.7.4 CellEditType
Essential Grid for ASP.NET MVC supports CellEditType by using delegated controls for specific
data types such as the CheckBox control for Boolean data types; NumericTextBox control for
integers, double, and decimal types; DatePicker control for date-time data; and DropDownList
control for lists of data. The edit type of every column can be customized using the CellEditType
property.

Use Case Scenarios


The delegated control for specific data types eases usability and improves the client-side
validation.

Figure 125: Grid with Inline Row Editing

4.7.4.1 Configuring CellEditType

CellEditType can be configured in two ways:

© 2014 Syncfusion. All rights reserved. 351 | Page


Essential Grid for ASP.NET MVC Classic

 GridBuilder
 GridPropertiesModel

4.7.4.1.1 Through GridBuilder

The steps to configure the CellEditType features using GridBuilder are:


1. Add the MicrosoftMvcValidation.debug.js file in the master page.

[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

© 2014 Syncfusion. All rights reserved. 352 | Page


Essential Grid for ASP.NET MVC Classic

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application. Refer to How to > Adding a Model to the Application and
Editing > EditableOrder Class.
3. Create a strongly typed view. Refer to How to > Strongly Typed View.
4. In the view, use the Model property in the Datasource() to bind the data source.
5. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete.
6. Essential Grid allows adding new records through grid toolbar items. Refer to Concepts and
Features > Editing.
7. Specify the primary property which uniquely identifies the grid record. Specify the
GridEditing mode using the EditMode() method. Refer to Concepts and Features >
Editing.

View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");

© 2014 Syncfusion. All rights reserved. 353 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p =>
p.EmployeeID).HeaderText("Employee
ID").NumericEditParams(n=>n.MinValue(0).MaxValue(9));

column.Add(p =>
p.CustomerID).HeaderText("Customer
ID").CellEditType(CellEditType.MaskEdit).MaskEditParams(m =>
m.Mask("aaaaa").WaterMarkText("aaaaa"));

column.Add(p =>
p.Verified).HeaderText("Verified");
column.Add(p =>
p.ShipRegion).HeaderText("Ship
Region").CellEditType(CellEditType.DropdownEdit);

column.Add(p =>
p.Freight).HeaderText("Freight").CellEditType(CellEditType.PercentEdit)
.PercentEditParams(p=>p.MaxValue(100).MinValue(0));

})
.EnablePaging()
.EnableSorting()
.EnableGrouping()

%>

View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");

column.Add(p =>
p.EmployeeID).HeaderText("Employee
ID").NumericEditParams(n=>n.MinValue(0).MaxValue(9));

column.Add(p =>
p.CustomerID).HeaderText("Customer
ID").CellEditType(CellEditType.MaskEdit).MaskEditParams(m =>
m.Mask("aaaaa").WaterMarkText("aaaaa"));

column.Add(p =>
p.Verified).HeaderText("Verified");
column.Add(p =>
p.ShipRegion).HeaderText("Ship
Region").CellEditType(CellEditType.DropdownEdit);

© 2014 Syncfusion. All rights reserved. 354 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p =>
p.Freight).HeaderText("Freight").CellEditType(CellEditType.PercentEdit)
.PercentEditParams(p=>p.MaxValue(100).MinValue(0));

})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.Render();
}

8. In the controller, create a method to add new records to the grid as shown in the following
code. In this example, the repository method Add() is being created to insert records in the
database. Refer to the repository action method given below.

Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add used to insert records into the
data source.
OrderRepository.Add(ord);

//After adding the record into database, refresh the grid.


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes from Editing>OrderRepository Class.

9. In the controller, create a method to save changes as shown in the following code sample.
In this example, the repository method Update() is used to update records to the data
source.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update is used to update the
records into the datasource.
OrderRepository.Update(ord);

//After saving the records into the datasource refresh the


grid.

© 2014 Syncfusion. All rights reserved. 355 | Page


Essential Grid for ASP.NET MVC Classic

var data = OrderRepository.GetAllRecords();


return data.GridActions<EditableOrder>();
}

10. Run the application. The grid will appear as shown below:

Figure 126: Grid with Toolbar Options for Editing, Inserting, and Deleting

The following screenshot shows default editor-type controls such as NumericTextBox for integer
types (namely “Employee ID”), NumericTextbox for decimal types (namely “Freight”), and
CheckBox for Boolean types (namely “Verified” column).

© 2014 Syncfusion. All rights reserved. 356 | Page


Essential Grid for ASP.NET MVC Classic

Figure 127: Grid with Inline Row Editing

Figure 128: Grid with Inline Row Inserting

© 2014 Syncfusion. All rights reserved. 357 | Page


Essential Grid for ASP.NET MVC Classic

4.7.4.1.2 Through GridPropertiesModel

The steps to work with the CellEditType feature using GridPropertiesModel are as follows:

1. Add the MicrosoftMvcValidation.debug.js file in the master page.

[Site.Master]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>
28.

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

© 2014 Syncfusion. All rights reserved. 358 | Page


Essential Grid for ASP.NET MVC Classic

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application. Refer to How to>Adding a Model to the Application and
Editing>EditableOrder Class.
3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<Editing.Models.EditableOrder>("Orders_G
rid",

(GridPropertiesModel<Editing.Models.EditableOrder>)ViewData["GridModel"
]).ToString())%>

© 2014 Syncfusion. All rights reserved. 359 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]
@( Html.Syncfusion().Grid<Editing.Models.EditableOrder>("Orders_Grid",

(GridPropertiesModel<Editing.Models.EditableOrder>)ViewData["GridModel"
]).ToString()))

5. Create a GridPropertiesModel in the Index action and assign the grid properties in the
model.

Controller

var model = new GridPropertiesModel<EditableOrder>


{
Caption = "Order",
AllowPaging = true,
AllowGrouping = true,
AllowSorting = true,
AutoFormat = Skins.Sadune,
Height = 500,
DataSource = OrderRepository.GetAllRecords()
};
model.Columns = new List<GridColumn<EditableOrder>>
{
new GridColumn<EditableOrder>
{
HeaderText = "Order ID",
MappingName = "OrderID",
ColumnType=typeof(int)
},
new GridColumn<EditableOrder>
{
HeaderText = "Employee ID",
MappingName = "EmployeeID",
ColumnType = typeof(int),
CellEditType =
Syncfusion.Mvc.Grid.CellEditType.NumericEdit,
NumericEditParams = new NumericTextBoxModel(){
MinValue = 0, MaxValue = 9}
},
new GridColumn<EditableOrder>
{
HeaderText = "Customer ID",
MappingName = "CustomerID",
ColumnType=typeof(string),
CellEditType =
Syncfusion.Mvc.Grid.CellEditType.MaskEdit,
MaskEditParams = new MaskEditTextBoxModel(){
WaterMarkText = "aaaaa", Mask = "aaaaa"}

© 2014 Syncfusion. All rights reserved. 360 | Page


Essential Grid for ASP.NET MVC Classic

},
new GridColumn<EditableOrder>
{
HeaderText = "Verified",
MappingName = "Verified",
ColumnType=typeof(bool)
},
new GridColumn<EditableOrder>
{
HeaderText = "Ship Region",
MappingName = " ShipRegion ",
ColumnType=typeof(string),
CellEditType =
Syncfusion.Mvc.Grid.CellEditType.DropdownEdit
},
new GridColumn<EditableOrder>
{
HeaderText = "Freight",
MappingName = "Freight",
ColumnType=typeof(decimal),
CellEditType=
Syncfusion.Mvc.Grid.CellEditType.PercentEdit,
PercentEditParams = new PercentTextBoxModel(){
MinValue = 0, MaxValue = 100}

},
};
ViewData["GridModel"] = model;
return View();

6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AllowNew, AllowEdit, and AllowDelete.
7. Specify the grid editing mode using the EditMode property.
8. Specify the Primary property which uniquely identifies the grid record.
9. Add the edit setting to the model.
10. Essential Grid allows adding new records using grid toolbar items. Refer to Concepts and
Features>Editing.
11. In the controller, create a method to add new records to the grid as given below. In this
example, the repository method Add() is being created to insert records in the database.
Refer to the repository action method given in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
//Repository action method Add used for perform inserting
records into datasource
OrderRepository.Add(ord);

© 2014 Syncfusion. All rights reserved. 361 | Page


Essential Grid for ASP.NET MVC Classic

//After adding the record into database refresh the Grid


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

Note: Refer to the repository action codes in Editing>OrderRepository Class.

12. In the controller, create a method to save changes, as shown in the following code. In this
example, the repository method Update() is used to update records in the data source.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
//Repository action method Update used for perform update
the records into datasource
OrderRepository.Update(ord);

//After save the records into datasource refresh the Grid


var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

13. Run the application. The grid will appear as shown in the following screenshot.

© 2014 Syncfusion. All rights reserved. 362 | Page


Essential Grid for ASP.NET MVC Classic

Figure 129: Grid with Toolbar Options for Editing, Inserting, and Deleting Records

The following screenshot shows the default editor-type controls such as NumericTextBox for
integer types (namely “Employee ID”), NumericTextbox for decimal types (namely “Freight”), and
CheckBox for Boolean types (namely the “Verified” column).

© 2014 Syncfusion. All rights reserved. 363 | Page


Essential Grid for ASP.NET MVC Classic

Figure 130: Grid with Inline Row Editing

Figure 131: Grid with Inline Row Inserting

4.7.4.2 Tables for Properties, Methods, and Events


Properties

The following table illustrates the properties under GridColumn, which is relevant to
CellEditType functionality.

Name Description Type of Data type Value it accepts Dependen


property cy
CellEditTyp Used to set the Server-side CellEditType CellEditType.StringEdit, AllowEditing
e CellEditType of
CellEditType.BooleanEdit,
the specified
column. CellEditType.
DropdownEdit,
CellEditType.
DateTimeEdit,

CellEditType. MaskEdit,

© 2014 Syncfusion. All rights reserved. 364 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Type of Data type Value it accepts Dependen


property cy
CellEditType. PercentEdit,

CellEditType. NumericEdit

NumericEdi Used to set Server-side NumericText NumericTextBoxModel CellEditType


tParams NumericEditPa BoxModel Object
rams when the
CellEditType is
NumericEdit.

PercentEdit Used to set Server-side PercentText PercentTextBoxModel CellEditType


Params PercentEditPar BoxModel Object
ams when the
CellEditType is
PercentEdit.

MaskEditP Used to set Server-side MaskEditTe MaskEditTextBoxModel CellEditType


arams MaskEditParam xtBoxModel Object
s when the
CellEditType is
MaskEdit.

AllowForma Used to set the Server-side Boolean True/false AllowEditing


tinEditMode AllowFormatin
EditMode. If
any format is
applied to the
column, then
when editing, it
decides whether
the format is
required or not.

Note: Refer to Tools MVC>NumericTextbox UG to set NumericEditParams

Refer to Tools MVC>PercentTextbox UG to set PercentEditParams

Refer to Tools MVC>MaskEditTextbox UG to set MaskEditParams

The following table illustrates the CellEditType option usages and controls.

CellEditType Control Usage


CellEditType.StringEdit(Default) Textbox Used to edit any string

© 2014 Syncfusion. All rights reserved. 365 | Page


Essential Grid for ASP.NET MVC Classic

CellEditType Control Usage


valued column.

CellEditType.BooleanEdit Checkbox Used to specify true or false


by checking and unchecking
respectively.

CellEditType.DropdownEdit DropdownList Used to select from a list of


values in the column.

CellEditType.NumericEdit NumericTextbox Used to edit integers, double


or decimals.

CellEditType.PercentEdit PercentTextbox Used to edit integer, double


or decimal with display string
appended to percent symbol.

CellEditType.MaskEdit MaskEditTextbox Used to mask any common


string to the column.

CellEditType.DateTimeEdit Datepicker Used to directly set the date.

Sample Link
To view the samples:
29. Open the ASP.NET MVC Sample Browser from the dashboard. (Refer to the Samples and
Location chapter)
30. Navigate to Grid>Editing>Cell Edit Type demo.

4.7.5 Excel-Like Editing in MVC Grid


This feature allows you to edit various fields of the grid at the same time, allowing you the ease of
Excel-like functionality in editing data.
The edited data is stored in the client side temporarily before it is saved on the server side
manually or at a fixed time interval.
Out of the two modes of grid editing (i.e. server mode and JSON mode), this feature is only
supported in JSON mode.

Use Case Scenario


Users can edit large amounts of data all at the same time and then save it on to the server at
once, instead of waiting for the server to save edited data before making another edit.

Feature Summary

© 2014 Syncfusion. All rights reserved. 366 | Page


Essential Grid for ASP.NET MVC Classic

The Excel-like edit feature allows you to edit data similarly to how one can edit it using Microsoft
Excel. This is more suitable for extremely large edits, since it reduces the time required to save all
the edited data to the server side.
This feature in Essential Grid for MVC has two modes:
 Manual Excel—This allows you to edit large amounts of data and then save it on to the
server side whenever you need to.
 Auto Excel—This option automatically updates the server with edited information, at fixed
time intervals.
Both of these modes allow you to keep editing as much data as required for as long as required.
Edited data is marked on the grid so that you know which fields or cells have been edited.
These markers are not shown after the updated data is rendered.
The following figure gives you a basic idea of the appearance of a grid in the Excel-like edit
mode:

Figure 132: Excel-Like Editing in a Grid

Properties

Type of
Property Description Value it accepts Dependencies
property

© 2014 Syncfusion. All rights reserved. 367 | Page


Essential Grid for ASP.NET MVC Classic

Depends on
AllowEditing—

Specifies the edit GridEditMode  AutoExcel


EditMode If AllowEditing is set
mode. (Enum)  ManualExcel
to True, the
EditMode property is
enabled.

Depends on
EditMode—
Used to specify the
time interval at which int
TimeSpan Any integer value
data is saved to the Only if the EditMode
server. is set to AutoExcel
will this property will
be activated.

Events

Name Description Arguments

 colObj—columnObject
contains information about
column objects such as
Triggered before the edit form of the cell name, type, header text, etc.
OnCellEdit
being edited is rendered.

 value—Contains the value of


the cell being edited.

 colObj—columnObject
contains information about
column objects, such as
Triggered before the value of the
name, type, header text, etc.
OnCellSave particular cells being edited are saved in
the client side.
 value—Contains the updated
value of the cell.

 updatedRecords—contains
Triggered before the updated records are the list of updated records.
OnBulkSave
saved in the server side.

© 2014 Syncfusion. All rights reserved. 368 | Page


Essential Grid for ASP.NET MVC Classic

 deletedRecords—contains
the list of deleted records.

 insertedRecords—contains
the list of inserted records.

 colObj—columnObject
contains information about
column objects such as
Triggered before the updated records are name, type, header text, etc.
OnCancel
canceled for saving in the server side.

 value—Contains the value of


the cell being edited.

4.7.5.1 Enabling Excel-Like Editing in MVC Grid

A grid can be rendered in two ways:


 Through Server mode
 Through JSON mode
Out of these two modes, Excel-like editing is only supported by the JSON mode.

4.7.5.1.1 Through GridBuilder


The steps to work with the editing feature through GridBuilder are as follows:
1. Add the MicrosoftMvcValidation.debug.js file in the master page.
View[ASPX]

<head runat="server">

<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"


/></title>

………

<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

© 2014 Syncfusion. All rights reserved. 369 | Page


Essential Grid for ASP.NET MVC Classic

31.
[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"

© 2014 Syncfusion. All rights reserved. 370 | Page


Essential Grid for ASP.NET MVC Classic

type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Create a strongly typed view.
4. In the view, use the Model property in the Datasource() to bind the data source.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)

.Caption("Orders")
.Column(column =>
{

column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})

%>

View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)

.Caption("Orders")
.Column(column =>
{

© 2014 Syncfusion. All rights reserved. 371 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})

.Render();

5. Enable the Excel-like editing mode by setting the edit mode to AutoExcel (or ManualExcel)
and configuring the editing property AllowEdit which specifies the action method.This will
perform the save operation, as displayed below.Set the TimeSpan property which is used in
saving the records automatically after the specified time interval in the AutoExcel edit mode.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)

.Editing( edit=>{
edit.AllowEdit(true, "Home/BulkSave");// Specify the action method
which will perform the update action.
edit.EditMode(GridEditMode.AutoExcel);// Specify the grid edit mode.
edit.TimeSpan(3000);
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary
key to primary key collections.
})
%>

View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)

.Editing( edit=>{
edit.AllowEdit(true, "Home/BulkSave");// Specify the controller and

© 2014 Syncfusion. All rights reserved. 372 | Page


Essential Grid for ASP.NET MVC Classic

action method which will perform the update action.


edit.EditMode(GridEditMode.AutoExcel);// Specify the grid edit mode.
edit.TimeSpan(3000);
edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary
key to primary key collections.
})
.Render();
}
AS

Note: If you want to specify the URL in the AllowEdit property itself means, specify the controller
and the corresponding action name as a URL. If you using the Mappers property then there is no
need to specify the controller name.

6. Essential Grid allows adding new records through grid toolbar items. In this
example, AddNew, Edit, Delete, Save, and Cancel buttons have been added as toolbar
items as displayed below:
View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)

.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for inserting
records.
.Add(GridToolBarItems.Edit) )// Toolbar item for editing
records.
.Add(GridToolBarItems.Delete)// Toolbar item for deleting
records.
.Add(GridToolBarItems.Update)// Toolbar item for saving
records.
.Add(GridToolBarItems.Cancel);// Toolbar item for canceling
request.
})
%>

View[cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)

.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for inserting
records.
.Add(GridToolBarItems.Edit) )// Toolbar item for editing
records.
.Add(GridToolBarItems.Delete)// Toolbar item for deleting
records.

© 2014 Syncfusion. All rights reserved. 373 | Page


Essential Grid for ASP.NET MVC Classic

.Add(GridToolBarItems.Update)// Toolbar item for saving


records.
.Add(GridToolBarItems.Cancel);// Toolbar item for canceling
request.
})
.Render();

7. In the controller, create a method to save changes as displayed below. In this example, the
repository method BulkSave() is used to update records to the data source. In the function
below, we can get the list of updated records through the parameter updatedRcds using
the bind prefix updatedRecords. In the same way we can get the list of added and deleted
records using the bind prefix addedRecords and deletedRecords respectively.

Controller

///<summary>
/// Used to update the records in the database and refresh the grid.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BulkSave([Bind(Prefix =
"updatedRecords")]IEnumerable<EditableOrder> updatedRcds, [Bind(Prefix
= "addedRecords")]IEnumerable<EditableOrder> addedRcds, [Bind(Prefix =
"deletedRecords")]IEnumerable<EditableOrder> deletedRcds)
{
if (updatedRcds != null)
OrderRepository.Update(updatedRcds);
if (addedRcds != null)
OrderRepository.Add(addedRcds);
if (deletedRcds != null)
OrderRepository.Delete(deletedRcds);
// After the records are saved to the data source, refresh the
grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

8. Run the application and edit the data as displayed below:

© 2014 Syncfusion. All rights reserved. 374 | Page


Essential Grid for ASP.NET MVC Classic

Figure 133: Excel-Like Edit through GridBuilder

32. The updated cells will be indicated bythe red color mark. The changes will be saved
automatically after the specified time interval.

4.7.5.1.2 Through GridPropertiesModel


The steps to work with the editing feature through GridPropertiesModel are as follows:

1. Add the MicrosoftMvcValidation.debug.js file in the master page.


View[ASPX]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"

© 2014 Syncfusion. All rights reserved. 375 | Page


Essential Grid for ASP.NET MVC Classic

type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%

© 2014 Syncfusion. All rights reserved. 376 | Page


Essential Grid for ASP.NET MVC Classic

>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file to create the Grid control in the view.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p => p.Delivered).HeaderText("Delivered");
})

})%>

View[cshtml]

@{Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p => p.Delivered).HeaderText("Delivered");
})
.Render();
)}

5. Create a GridPropertiesModel in the Index method and assign the grid


properties in the model.

© 2014 Syncfusion. All rights reserved. 377 | Page


Essential Grid for ASP.NET MVC Classic

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping = true,
AutoFormat = Skins.Sandune,
ActionMode = ActionMode.JSON
};

ViewData["GridModel"] = model;

33.
6. Enable the Excel-like editing mode by setting the edit mode to AutoExcel (or
ManualExcel). Configure the editing property AllowEdit which specifies the
action method that will perform the save operation as displayed below. Set the
TimeSpan property which is used in saving the records automatically after the
specified time interval in AutoExcel edit mode.

Controller

GridEditing edit=new GridEditing();


edit.EditMode = GridEditMode.AutoExcel;
edit.TimeSpan = 3000;
edit.AllowEdit = true;
edit.GridSaveMapper = "BulkSave";

7. Specify the primary property which uniquely identifies the grid record.

Controller

// Add the PrimaryKey value to uniquely identify the record.


edit.PrimaryKey = new List<string>() { "OrderID" };
34.
8. Add the edit setting to the model.
35.
Controller

// Add the edit setting to the model.


model.Editing = edit;

© 2014 Syncfusion. All rights reserved. 378 | Page


Essential Grid for ASP.NET MVC Classic

9. Grid allows adding new records through grid toolbar items. In this example,
AddNew, Edit, Delete, Save, and Cancel buttons have been added in the toolbar
items. Therefore, configure the toolbar, as displayed below:
36.
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();

toolbar.Enable = true;

// Add the Add New, Edit, Delete, Save, and Cancel buttons to the
toolbar.

toolbar.Items.Add(new ToolbarOptions() { ItemType=


GridToolBarItems.AddNew});
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Delete });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Update });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Cancel });

model.ToolBar = toolbar;

10. In the controller, create a method to save changes, as displayed below. In this
example, the repository method BulkSave() is used to update records to the data
source. In the below function, we can get the list of updated records through
parameter “updatedRcds” using the bind prefix "updatedRecords". In the same
way we can get the list of added and deleted records using the bind prefix
“addedRecords” and “deletedRecords” respectively.
Controller

///<summary>
/// Used to update the records in the database and refresh the grid.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BulkSave([Bind(Prefix =
"updatedRecords")]IEnumerable<EditableOrder> updatedRcds, [Bind(Prefix
= "addedRecords")]IEnumerable<EditableOrder> addedRcds, [Bind(Prefix =
"deletedRecords")]IEnumerable<EditableOrder> deletedRcds)
{
if (updatedRcds != null)
OrderRepository.Update(updatedRcds);
if (addedRcds != null)
OrderRepository.Add(addedRcds);
if (deletedRcds != null)

© 2014 Syncfusion. All rights reserved. 379 | Page


Essential Grid for ASP.NET MVC Classic

OrderRepository.Delete(deletedRcds);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

11. Run the application and edit the data as displayed below:
37.

Figure 134: Excel-Like Edit throughGridProperties Model

38. The updated cells will be indicated by using the red color mark. The changes will be saved
automatically after the specified time interval.
39.
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Excel Like Edit
40.

4.7.6 Dialog editing in MVC Grid


This feature allows you to edit various fields of a single record at the same time.
The following figure gives you a basic idea of the structure and appearance of Grid in the Dialog
edit mode:

© 2014 Syncfusion. All rights reserved. 380 | Page


Essential Grid for ASP.NET MVC Classic

Figure 135: Dialog Editing in Grid

The Dialog Edit feature allows you to edit data, using a dialog box, which contains fields
associated with the data record being edited.
You can edit data in two ways using this feature:
 Using the Dialog mode—This allows you to edit data of a particular record using the
Dialog box. You can only edit the data stored in the fields that you have rendered to be
visible.

 Using the Dialog Template mode—This allows you to create a template for the data
that you require to be edited using the Dialog Box.
This means you can edit any of the fields pertaining to a single record of data and apply it
to a template so that the same format is applied for all the other records that you will edit
later.

Use Case Scenario


The user can edit fields that are associated with a single data record, using the dialog box that
appears.

4.7.6.1 Properties and Events Tables


Properties

© 2014 Syncfusion. All rights reserved. 381 | Page


Essential Grid for ASP.NET MVC Classic

Descriptio Type of Value it Dependenc Sub-


Property
n property accepts ies properties
Depends on
AllowEditing--

Dialog
Specifies the GridEditMode
EditMode If AllowEditing NA
Edit mode DialogTe
(Enum) is set to True,
mplate
the EditMode
property is
enabled.

Height—
Specifies the
height of the
dialog.
Width—
Specifies the
Width of the
dialog.
Resizable—
Specifies
Depends on whether the
Dialog dialog is
This property EditMode—
related resizable.
contains all values
the dialog Syncfusion.Mv Draggable—
(depends
Dialog c.Tools.Dialog If EditMode is Specifies
related on the
Model set to True, whether the
properties sub-
the Dialog dialog can be
properties
property is dragged or not.
used)
enabled.
MaxHeigh—
Specifies the
maximum
height of the
dialog box.
MaxWidth—
Specifies the
minimum width
of the dialog
box.
MinHeight—

© 2014 Syncfusion. All rights reserved. 382 | Page


Essential Grid for ASP.NET MVC Classic

Descriptio Type of Value it Dependenc Sub-


Property
n property accepts ies properties
Specifies the
minimum
height of the
dialog box.
MinWidth—
Specifies the
minimum width
of the dialog
box.
Show—
Specifies the
animation type
of the dialog
box when it
opens.
Hide—Specifies
the animation
type of the
dialog box when
it closes.
Position—
Specifies the
position of the
dialog.

Depends on
EditMode—
Specifies the
name of the If DialogMode
DialogModeE Template in is set to
string Any string DialogTempla NA
ditorTemplate the Dialog
Template te then
mode DialogModeE
ditorTemplate
is enabled.

Events

© 2014 Syncfusion. All rights reserved. 383 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Arguments Type


This event is triggered
when a dialog attempts
to close. If the
ClientSideBeforeClose beforeclose event
event NA
handler (callback
function) returns false,
the close will be
prevented.

ClientSideClose This event is triggered


when the dialog is event NA
closed.

ClientSideFocus This event is triggered


when the dialog gains event NA
focus.

This event is triggered


ClientSideOpen event NA
when dialog is opened.

4.7.6.2 Enabling Dialog Editing in MVC Grid


A grid can be rendered in two ways:

4.7.6.2.1 Through GridBuilder


The steps to work with the editing feature through GridBuilder are as follows:
1. Add the MicrosoftMvcValidation.debug.js file in the master page.
View[ASPX]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

© 2014 Syncfusion. All rights reserved. 384 | Page


Essential Grid for ASP.NET MVC Classic

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script

© 2014 Syncfusion. All rights reserved. 385 | Page


Essential Grid for ASP.NET MVC Classic

src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Create a strongly typed view.
4. In the view, use the Model property in the Datasource() method to bind the data source.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{

column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})

%>

View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{

column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>

© 2014 Syncfusion. All rights reserved. 386 | Page


Essential Grid for ASP.NET MVC Classic

p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})

.Render();
}

5. Enable Dialog editing mode by setting the edit mode to Dialog and configure the dialog and
editing properties such as allow new, allow edit, and allow delete, as displayed below:

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.Dialog(dialog =>
{
dialog.Height(500);
dialog.Width(460);
dialog.Position(DialogPositions.Center);
dialog.Show(DialogAnimations.bounce);
dialog.Hide(DialogAnimations.fold);
});
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert
action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the Delete
action.

})
%>

View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.Dialog(dialog =>
{
dialog.Height(500);
dialog.Width(460);
dialog.Position(DialogPositions.Center);
dialog.Show(DialogAnimations.bounce);
dialog.Hide(DialogAnimations.fold);
});

© 2014 Syncfusion. All rights reserved. 387 | Page


Essential Grid for ASP.NET MVC Classic

edit.AllowEdit(true, "Home/OrderSave")// Specify the controller


and action method which will perform the update action.
.AllowNew(true, "Home/AddOrder")// Specify the controller and
action method which will perform the insert action.
.AllowDelete(true, "Home/DeleteOrder");// Specify the controller
and action method which will perform the delete action.
}).Render();
}

Note: If you want to specify the URL in the AllowEdit property itself, specify the controller and
the corresponding action name as a URL. If you using the Mappers property then there is no need to
specify the controller name.

6. Grid allows adding new records through grid toolbar items. In this example, AddNew, Edit,
Delete, Save, and Cancel buttons have been added in the toolbar items. Therefore,
configure the toolbar as displayed below:

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)

.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for inserting
records.
.Add(GridToolBarItems.Edit) )// Toolbar item for editing
records.
.Add(GridToolBarItems.Delete)// Toolbar item for deleting
records.
.Add(GridToolBarItems.Update)// Toolbar item for saving
changes.
.Add(GridToolBarItems.Cancel);// Toolbar item for canceling
request.
})
%>

View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)

.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for inserting
records.

© 2014 Syncfusion. All rights reserved. 388 | Page


Essential Grid for ASP.NET MVC Classic

.Add(GridToolBarItems.Edit) )// Toolbar item for editing


records.
.Add(GridToolBarItems.Delete)// Toolbar item for deleting
records.
.Add(GridToolBarItems.Update)// Toolbar item for saving
changes.
.Add(GridToolBarItems.Cancel);// Toolbar item for canceling
request.
})
.Render();

7. Specify the primary property which uniquely identifies the grid record.
41.
View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{

edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary key to


primary key collections.
})
%>

View[Razor]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{

edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary key to


primary key collections.
})
.Render();
}

8. In the controller, create a method to add new records to grid, as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer the repository action method displayed below.

Controller

/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the

© 2014 Syncfusion. All rights reserved. 389 | Page


Essential Grid for ASP.NET MVC Classic

grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

9. In the controller, create a method to save changes as displayed below.

In this example, the repository method Update() is used to update records to the data source.

Controller

/// Used to insert the record into database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data is displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update() is used to update the records in
the data source.
OrderRepository.Update(ord);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

10. In the controller, create a method to delete the records from the database as displayed
below.

In this example, the repository action Delete() will delete the record from the data source.

Controller

/// <summary>
/// Used to delete the records from the data source and refresh the
grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>

© 2014 Syncfusion. All rights reserved. 390 | Page


Essential Grid for ASP.NET MVC Classic

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

11. Run the application and double click any record to edit. The grid will appear as displayed
below.

Figure 136: Dialog edit through Grid Builder

4.7.6.2.2 Through GridPropertiesModel


The steps to work with the editing feature through GridPropertiesModel are as follows.

1. Add the MicrosoftMvcValidation.debug.js file in the master page.


View[ASPX]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"

© 2014 Syncfusion. All rights reserved. 391 | Page


Essential Grid for ASP.NET MVC Classic

type="text/javascript"></script>
</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .

© 2014 Syncfusion. All rights reserved. 392 | Page


Essential Grid for ASP.NET MVC Classic

<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the Index.aspx file, to create the Grid control in View.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country;
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight;
column.Add(p => p.Delivered).HeaderText("Delivered");
})

})%>

View[cshtml]

@{Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country;
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight;
column.Add(p => p.Delivered).HeaderText("Delivered");
})
.Render();
)}

© 2014 Syncfusion. All rights reserved. 393 | Page


Essential Grid for ASP.NET MVC Classic

5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Sandune
};

ViewData["GridModel"] = model;

6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AllowNew, AllowEdit, and AllowDelete, as displayed below.

Controller
// Create an object for grid editing and enable the edit, add
new, and delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true, AllowDelete =
true, AllowNew = true };
// Set the action mappers for the insert, delete, and save actions.
edit.DeleteMapper = "DeleteOrder";
edit.InsertMapper = "AddOrder";
edit.GridSaveMapper = "OrderSave";

7. Customize the dialog as shown below:


Controller

DialogModel dialog = new DialogModel();


dialog.Height = 500;
dialog.Width = 460;
dialog.Show = DialogAnimations.bounce;
dialog.Hide = DialogAnimations.fold;
dialog.Position = DialogPositions.Center;
edit.Dialog = dialog;

8. Specify the GridEditMode through the EditMode property.

Controller
// Set the Edit mode.

© 2014 Syncfusion. All rights reserved. 394 | Page


Essential Grid for ASP.NET MVC Classic

edit.EditMode = GridEditMode.Dialog;

9. Specify the primary property which uniquely identifies the grid record.

Controller
// Add the PrimaryKey value to uniquely identify the record.
edit.PrimaryKey = new List<string>() { "OrderID" };

10. Add the edit object to the model.


Controller
// Add the edit object to the model.
model.Editing = edit;

42.
43. Essential Grid allows adding new records through grid toolbar items. In this example,
AddNew, Edit, Delete, Save, and Cancel buttons have been added as toolbar items as
displayed below:
Controller
// Configure the toolbar.
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
// Add the AddNew, Edit, Delete, Save, and Cancel buttons to the
toolbar.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.AddNew});
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Delete });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Update });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Cancel });
model.ToolBar = toolbar;

11. In the controller, create a method to add new records to grid, as displayed below. In this
example, the repository method Add() is being created to insert records in the database.
Refer to the repository action method displayed below.

Controller

/// <summary>
/// Used to insert the record in the database and refresh the grid.
/// </summary>

© 2014 Syncfusion. All rights reserved. 395 | Page


Essential Grid for ASP.NET MVC Classic

/// <param name="ord">Editable order.</param>


/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record to the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

12. In the controller, create a method to save changes as displayed below.

In this example, the repository method Update() is used to update records to the data source:
Controller

/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the records into
datasource.
OrderRepository.Update(ord);
//After saving the records into datasource refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

13. In the controller, create a method to delete the records from the database as displayed
below.

In this example, the repository action Delete() will delete the record from the data source.
Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]

© 2014 Syncfusion. All rights reserved. 396 | Page


Essential Grid for ASP.NET MVC Classic

public ActionResult DeleteOrder(int OrderID)


{
// Repoistory action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

14. Run the application. The grid will appear as displayed below.

Figure 137: Dialog Editing through the GridPropertiesModel

4.7.6.3 Edit Mode Configuration


Essential Grid provides two types for dialog editing mode. To change the editing mode, use the
EditMode() method as shown in the following code sample:

View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Editing( edit=>{
edit.EditMode(GridEditMode.Dialog);// Specify the grid edit
mode.

© 2014 Syncfusion. All rights reserved. 397 | Page


Essential Grid for ASP.NET MVC Classic

})%>

View[cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Editing( edit=>{
edit.EditMode(GridEditMode.Dialog);// Specify the grid edit
mode.

}).Render();

The grid will appear in the dialog editing mode as displayed below:

Figure 138: Dialog Edit Mode

If you want to use the DialogTemplate mode, follow the steps displayed below.
1. Create the template in partial view, as displayed below

View[ASPX]
<fieldset>
<legend>Fields</legend>
<div class="tablediv">

© 2014 Syncfusion. All rights reserved. 398 | Page


Essential Grid for ASP.NET MVC Classic

<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.OrderID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.OrderID) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.CustomerID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.CustomerID)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.EmployeeID) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.EmployeeID)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipName) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipName) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>

© 2014 Syncfusion. All rights reserved. 399 | Page


Essential Grid for ASP.NET MVC Classic

model.ShipName) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipAddress) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipAddress)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipCity) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipCity) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipRegion) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.ShipRegion)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.ShipCountry) %>
</div>
<div class="editor-field">

© 2014 Syncfusion. All rights reserved. 400 | Page


Essential Grid for ASP.NET MVC Classic

<%=
Html.Syncfusion().TextBoxFor(model => model.ShipCountry)
%>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry) %>
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.Freight) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.Freight) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.Freight) %>
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
<%= Html.Syncfusion().LabelFor(model
=> model.OrderDate) %>
</div>
<div class="editor-field">
<%=
Html.Syncfusion().TextBoxFor(model => model.OrderDate,
String.Format("{0:g}", Model.OrderDate)) %>
<%=
Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate) %>
</div>
</div>
</div>
</div>
</fieldset>

View [Razor]

<fieldset>
<legend>Fields</legend>
<div class="tablediv">
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.OrderID)
</div>

© 2014 Syncfusion. All rights reserved. 401 | Page


Essential Grid for ASP.NET MVC Classic

<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.CustomerID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.CustomerID)
@Html.Syncfusion().ValidationMessageFor(model =>
model.CustomerID)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.EmployeeID)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.EmployeeID)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.EmployeeID)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipName)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipName)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipName)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipAddress)

© 2014 Syncfusion. All rights reserved. 402 | Page


Essential Grid for ASP.NET MVC Classic

</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipAddress)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipAddress)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.ShipCity)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipCity)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCity)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipRegion)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.ShipRegion)
@ Html.Syncfusion().ValidationMessageFor(model =>
model.ShipRegion)
</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.ShipCountry)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model
=>model.ShipCountry)
@Html.Syncfusion().ValidationMessageFor(model =>
model.ShipCountry)
</div>
</div>
</div>
<div class="rowdiv">
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model => model.Freight)
</div>

© 2014 Syncfusion. All rights reserved. 403 | Page


Essential Grid for ASP.NET MVC Classic

<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.Freight)
@Html.Syncfusion().ValidationMessageFor(model =>

model.Freight)

</div>
</div>
<div class="celldiv" style="height: auto">
<div class="editor-label">
@Html.Syncfusion().LabelFor(model =>
model.OrderDate)
</div>
<div class="editor-field">
@Html.Syncfusion().TextBoxFor(model =>
model.OrderDate,String.Format("{0:g}", Model.OrderDate))
@Html.Syncfusion().ValidationMessageFor(model =>
model.OrderDate)
</div>
</div>
</div>
</div>
</fieldset>

Note: Don’t specify the form in the template. And the <fieldset> tag is required to surround the
template input fields else the buttons will not be displayed by the dialog.
44.
45. Configure the GridEditMode as DialogTemplate Mode and specify the name of the partial
view which contains the templates, as displayed below:

View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Editing( edit=>{
edit.DialogModeEditorTemplate("OrderEditorTemplate");
edit.EditMode(GridEditMode.DialogTemplate);// Specify the grid
edit mode.

})%>

View[cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Editing( edit=>{

© 2014 Syncfusion. All rights reserved. 404 | Page


Essential Grid for ASP.NET MVC Classic

edit.DialogModeEditorTemplate("OrderEditorTemplate");

edit.EditMode(GridEditMode.DialogTemplate);// Specify the grid


edit mode.

}).Render();

46. In the DialogTemplate mode, you should handle the insert action and the edit action.

To achieve this, check the RequestType property from PagingParams. If the request type is
either BeginEdit or BeginAddNew, then render the template by using the PartialView() method,
as displayed below.

Controller
/// <summary>
/// Paging and editing requests are mapped to
this method. This method invokes the HtmlActionResult
/// from the grid. The required response is
generated.
/// </summary>
/// <param name="args">Contains paging
properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed
in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args
,int? OrderID)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
// Check if the current request is an Edit
request and the edit mode is TemplateForm mode. Then
call the PartialView() to render the template.
if (currentRequest == RequestType.BeginEdit)
{
EditableOrder ord =
(EditableOrder)OrderRepository.Select(OrderID);
return
PartialView("OrderEditorTemplate", ord);
}
else if (currentRequest ==
RequestType.BeginAddNew)
{
// Check if the current request is an
AddNew request and edit mode is TemplateForm mode. Then

© 2014 Syncfusion. All rights reserved. 405 | Page


Essential Grid for ASP.NET MVC Classic

call the Partialview() to render the template.


return
PartialView("OrderEditorTemplate", new EditableOrder());
}
else
{
IEnumerable data =
OrderRepository.GetAllRecords();
return
data.GridActions<EditableOrder>();
}
}

47. The grid will appear in the dialog template editing mode as displayed below:

Figure 139: Dialog Template Edit Mode

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Dialog Editing

© 2014 Syncfusion. All rights reserved. 406 | Page


Essential Grid for ASP.NET MVC Classic

4.7.7 External Form Edit Mode


The External Form Edit Mode helps you to edit various data entries in the grid, one at a time,
using an external edit form. It can contain the fields that you require, in the custom external form
template that you would like to use.
This is different from the dialog editing mode in that it allows you to see the other entries in the
Grid while you are editing one.

You can position the edit form either in the top-right corner (by default), bottom-left left corner of
the Grid; or in a custom location, using a target ID, if you choose.
Use Case Scenario
This feature allows you to view the data you edit more clearly, while offering an uncompromised
view of the other data entries in the grid.
Appearance and Structure
The following figures illustrate the appearance and structure of the ExternalForm EditMode
feature, and its settings:

Figure 140: External Form Edit Mode with External Form in the top-right of the Grid

© 2014 Syncfusion. All rights reserved. 407 | Page


Essential Grid for ASP.NET MVC Classic

Figure 141: External Edit Form in the bottom-left of the Grid

Figure 142: External Form Edit Mode with Customized Template (Custom Fields in Grid)

If you have a customized template that you would like to use for the external edit form, this
feature allows you to use it. You may have new fields and customized dimensions that you can
use for the edit form.

© 2014 Syncfusion. All rights reserved. 408 | Page


Essential Grid for ASP.NET MVC Classic

Note: The default skin overrides your template’s skin.

Figure 143: External Edit Form with Custom Position (Target ID)

When you set the target ID for the ExternalForm EditMode, you will not only be able to customize
the position of the edit form, but also the skin used.
The target ID (of the element in the page) allows you to place the edit form anywhere on the
same page as the grid. If in case the element doesn’t exist on the page, you will not be able to
place the edit form in that location.

Note: The custom skin of your edit form template is not overridden by the default skin used by
the edit form, if you choose this option.

4.7.7.1 Properties
Type of
Property Description Value it accepts Dependencies
property

Depends on
AllowEditing—
GridEditMode  ExternalForm
EditMode Specifies the Edit Mode
(Enum)  ExternalFormTemplate If AllowEditing is set to
True, the EditMode
property is enabled.

Depends on
 Position.TopRight, ExternalForm—
Specifies position of the
Position Enum  Position.BottomLeft,
external form
 Position.Custom If GridEditMode is
External Form, position

© 2014 Syncfusion. All rights reserved. 409 | Page


Essential Grid for ASP.NET MVC Classic

of the external form is


posibile.

Specifies the target ID


TargetID String Any String ExternalForm
of External Edit Form

4.7.7.2 Enabling External Form Edit Mode in Grid MVC


You can enable this feature using either one of the following procedures:

4.7.7.2.1 Through GridBuilder


The steps to enable the External From Edit Mode feature through GridBuilder are as follows:
1. Create a model in the application.
2. Create a strongly typed view. Add the MicrosoftMvcValidation.debug.js file in the master
page.

View[ASPX]
<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>

48.
[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>
49.

© 2014 Syncfusion. All rights reserved. 410 | Page


Essential Grid for ASP.NET MVC Classic

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

1. In the view, use the Model property in the Datasource() to bind the data source.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.Caption("Orders")
---------
.Column(column =>
{

© 2014 Syncfusion. All rights reserved. 411 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p => p.OrderID).HeaderText("Order ID");


column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order Date");
column.Add(p => p.Freight).HeaderText("Freight");

})
----------
%>

50.
View [cshtml]

@{Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model).ActionMode(ActionMode.JSON)
.Caption("Orders")
----------
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order Date");
column.Add(p => p.Freight).HeaderText("Freight");

})
----------

51.
52.
2. Essential Grid allows adding new records through grid toolbar items.
53.
In this example, AddNew, Edit, Delete, Save, and Cancel buttons have been added in the
toolbar items, as displayed below.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")

-------
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for
inserting records.
.Add(GridToolBarItems.Edit)// Toolbar item for
editing records.

© 2014 Syncfusion. All rights reserved. 412 | Page


Essential Grid for ASP.NET MVC Classic

.Add(GridToolBarItems.Delete)// Toolbar item for


deleting records.
.Add(GridToolBarItems.Update)// Toolbar item for
saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar item for
canceling request.
})
----------
%>

View[cshtml]

@{Html.Syncfusion().Grid<EditableOrder>("Grid1")

-------
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar item for
inserting records.
.Add(GridToolBarItems.Edit)// Toolbar item for
editing records.
.Add(GridToolBarItems.Delete)// Toolbar item for
deleting records.
.Add(GridToolBarItems.Update)// Toolbar item for
saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar item for
canceling request.
})
----------
}

3. Enable ExternalForm editing by using the Editing property and its sub-properties, as
displayed below.
54.
View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")

-------
.Editing(edit=>{
edit.ExternalForm(ef =>
{
ef.TargetID("ExternalEditForm");
ef.Position(ExternalFormPosition.TopRight);
});

© 2014 Syncfusion. All rights reserved. 413 | Page


Essential Grid for ASP.NET MVC Classic

// Specify the action method which will perform the update


action.
edit.AllowEdit(true, "Home/OrderSave")
// Specify the action method which will perform the insert
action.
.AllowNew(true, "Home/AddOrder")
// Specify the action method which will perform the delete
action.
.AllowDelete(true, "Home/DeleteOrder");
//Specify the grid edit mode.
edit.EditMode(GridEditMode.ExternalForm);
edit.ExternalModeEditorTemplate("OrderEditorTemplate");
// Add primary key to primary key collections
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
--------
%>

55.
56.
View[cshtml]

@{Html.Syncfusion().Grid<EditableOrder>("Grid1")

-------
.Editing(edit=>{
edit.ExternalForm(ef =>
{
ef.TargetID("ExternalEditForm");
ef.Position(ExternalFormPosition.TopRight);

});
// Specify the controller and action method which will
perform the update action.
edit.AllowEdit(true, "Home/OrderSave")
// Specify the controller and action method which will
perform the insert action.
.AllowNew(true, "Home/AddOrder")
// Specify the controller and action method which will
perform the delete action.
.AllowDelete(true, "Home/DeleteOrder");
// Specify the grid edit mode.
edit.EditMode(GridEditMode.ExternalForm);
edit.ExternalModeEditorTemplate("OrderEditorTemplate");
// Add primary key to primary key collections.
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
--------
}

© 2014 Syncfusion. All rights reserved. 414 | Page


Essential Grid for ASP.NET MVC Classic

Note: If you want to specify the URL in the AllowEdit property itself means, specify the controller
and the corresponding action name as a URL. If you using the Mappers property then there is no
need to specify the controller name.

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult ExternalFormEdit()
{
return View(OrderRepository.GetAllRecords());
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ExternalFormEdit(PagingParams args, int? OrderID,
GridEditMode? GridMode)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
if (currentRequest == RequestType.BeginEdit && GridMode ==
GridEditMode.ExternalFormTemplate)
{
EditableOrder ord = (EditableOrder)OrderRepository.Select(OrderID);

return PartialView("OrderEditorTemplate", ord);


}
else if (currentRequest == RequestType.BeginAddNew && GridMode ==
GridEditMode.ExternalFormTemplate)
{
return PartialView("OrderEditorTemplate", new EditableOrder());
}
else
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();

}
}

4.7.7.2.2 Through GridProperties model


The steps to work with the external form editing feature through GridPropertiesModel are as
follows.
1. Add the MicrosoftMvcValidation.debug.js file in the master page.

© 2014 Syncfusion. All rights reserved. 415 | Page


Essential Grid for ASP.NET MVC Classic

View[ASPX]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script

© 2014 Syncfusion. All rights reserved. 416 | Page


Essential Grid for ASP.NET MVC Classic

src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Create a strongly typed view (Refer to How to>Strongly Typed View).
4. Add the following code in the view to create the Grid control in the view.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>(
"Grid1", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order Date");
column.Add(p =>
p.Freight).HeaderText("Freight");
})
%>

View[cshtml]

@{Html.Syncfusion().Grid<EditableOrder>(
"Grid1", "GridModel",
column =>

© 2014 Syncfusion. All rights reserved. 417 | Page


Essential Grid for ASP.NET MVC Classic

{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.OrderDate).HeaderText("Order Date");
column.Add(p =>
p.Freight).HeaderText("Freight");
}).Render();
}

5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
57.
Controller

GridPropertiesModel<EditableOrder> gridModel = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
----------
Height = 225,
---------
};

ViewData["GridModel"] = gridModel;

6. Essential Grid allows adding new records through grid toolbar items.
58.
In this example, AddNew, Edit, Delete, Save, and Cancel buttons have been added in the
toolbar items, as displayed below.
Controller

GridEditing edit = new GridEditing() { AllowEdit = true, AllowDelete =


true, AllowNew = true };
// Set the action mappers for insert, delete, and save actions.
edit.DeleteMapper = "DeleteOrder";
edit.InsertMapper = "AddOrder";

© 2014 Syncfusion. All rights reserved. 418 | Page


Essential Grid for ASP.NET MVC Classic

edit.GridSaveMapper = "OrderSave";
edit.ExternalModeEditorTemplate = "OrderEditorTemplate";
edit.ExternalForm.Position = position == null ?
ExternalFormPosition.TopRight : (ExternalFormPosition)position;
edit.ExternalForm.TargetID = "ExternalFormEdit";
edit.EditMode = GridMode == null ? GridEditMode.ExternalForm :
(GridEditMode)GridMode;
edit.PrimaryKey = new List<string>() { "OrderID" };
gridModel.Editing = edit;

7. Enable editing by using the External form Editing property in the GridPropertiesModel
and configure the editing properties such as allow new, allow edit, and allow delete, as
displayed below
59.
Controller

ToolbarSettings toolbar = new ToolbarSettings();


toolbar.Enable = true;
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.AddNew });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Delete });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Update });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Cancel });
gridModel.ToolBar = toolbar;

Controller

public ActionResult ExternalFormEditJsonModel(GridEditMode? GridMode,


ExternalFormPosition? position)
{
GridPropertiesModel<EditableOrder> gridModel = new
GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
AllowGrouping = true,
AllowSorting = true,
Caption = "Orders",
AllowPaging = true,

© 2014 Syncfusion. All rights reserved. 419 | Page


Essential Grid for ASP.NET MVC Classic

AllowScrolling = false,
AllowFiltering = true,
Height = 225,
AutoFormat = Skins.Sandune,
ActionMode = ActionMode.JSON,
};

GridEditing edit = new GridEditing() { AllowEdit = true, AllowDelete =


true, AllowNew = true };
// Set the action mappers for insert, delete, and save actions.
edit.DeleteMapper = "JsonDeleteOrder";
edit.InsertMapper = "JsonAddOrder";
edit.GridSaveMapper = "JsonOrderSave";
edit.ExternalModeEditorTemplate = "OrderEditorTemplate";
edit.ExternalForm.Position = position == null ?
ExternalFormPosition.TopRight : (ExternalFormPosition)position;
edit.EditMode = GridMode == null ? GridEditMode.ExternalForm :
(GridEditMode)GridMode;
edit.PrimaryKey = new List<string>() { "OrderID" };
gridModel.Editing = edit;
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true;
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.AddNew });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Edit });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Delete });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Update });
toolbar.Items.Add(new ToolbarOptions() { ItemType =
GridToolBarItems.Cancel });
gridModel.ToolBar = toolbar;
ViewData["GridModel"] = gridModel;
return View();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ExternalFormEditJsonModel(PagingParams args, int?
OrderID, GridEditMode? GridMode)
{
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
if (currentRequest == RequestType.BeginEdit && GridMode ==
GridEditMode.ExternalFormTemplate)
{
EditableOrder ord = (EditableOrder)OrderRepository.Select(OrderID);

return PartialView("OrderEditorTemplate", ord);


}

© 2014 Syncfusion. All rights reserved. 420 | Page


Essential Grid for ASP.NET MVC Classic

else if (currentRequest == RequestType.BeginAddNew && GridMode ==


GridEditMode.ExternalFormTemplate)
{
return PartialView("OrderEditorTemplate", new EditableOrder());
}
else
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
}

8. Run the application and perform editing through an external form.


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > ExternalForm Editing

4.7.8 Unbound Column Editing


This feature allows you to edit various fields of the grid at the same time, allowing you the use of
the Edit, Update, and Delete buttons on the edited column itself. It will provide support in two
modes of grid editing (i.e. server mode and JSON mode).
The following figure gives you a basic idea of the appearance of a grid in the Excel-like edit
mode:

© 2014 Syncfusion. All rights reserved. 421 | Page


Essential Grid for ASP.NET MVC Classic

Figure 144: Grid with Unbound Column Editing

Use Case Scenario


The user can edit or delete the fields that are associated with a single data record using the Edit
and Delete button that appear on the edited record itself, instead of using the toolbar.

4.7.8.1 Properties Tables

Property Description Type Value it Accepts Dependencies

EditMode Specifies the edit GridEditMode Normal Depends on


mode. AllowEditing—
(Enum)
If AllowEditing is
set to True, the
EditMode
property is
enabled.

Commands properties:

Property Description Type Value it Dependencies


Accepts

© 2014 Syncfusion. All rights reserved. 422 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type Value it Dependencies


Accepts
Command Specifies the grid CommandTypes AddNew Depends on
command types. AllowEditing—
Edit
Update If AllowEditing is
set to True, the
Delete
EditMode
Cancel property is
enabled.
Custom

Text Specifies the text NA String Depends on


of the grid AllowEditing—
commands.
If AllowEditing is
set to True, the
EditMode
property is
enabled.
ImageUrl Specifies the NA Image String Depends on
image for grid AllowEditing—
commands.
If AllowEditing is
set to True, the
EditMode
property is
enabled.
ItemType Specifies the UnBoundItemTyp Hyperlink Depends on
UnBoundItemTyp es AllowEditing—
es of grid Button
commands. If AllowEditing is
set to True, the
EditMode
property is
enabled.
ItemOption Specifies the UnboundItemOpti TextOnly Depends on
UnBoundItemOpti ons AllowEditing—
ons of grid
commands ImageOnly If AllowEditing is
set to True, the
EditMode
ImagePlusText property is

© 2014 Syncfusion. All rights reserved. 423 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type Value it Dependencies


Accepts
enabled.

UnBound Specifies the Boolean True or False


column of grid
commands NA

Events
Event Description Arguments Type Reference links

OnCustomUn This event occurs when String handler


boundCellClic the unbound cell is Client-Side NA
kHandler clicked.

4.7.8.2 Appearance

Figure 145: Unbound Column Editing


Sample Link
To view the samples, follow the steps below:

© 2014 Syncfusion. All rights reserved. 424 | Page


Essential Grid for ASP.NET MVC Classic

1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Editing > Unbound Column Editing

4.7.8.3 Enabling Unbound Column Editing in MVC Grid


A grid can be rendered in two ways:

1. Through Grid Builder

2. Through GridPropertiesModel

4.7.8.3.1 Server Mode

4.7.8.3.1.1 Through GridBuilder


The steps to work with the unbound column editing feature through GridBuilder are as follows:

1. Add the MicrosoftMvcValidation.debug.js file in the master page.

View[ASPX]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

© 2014 Syncfusion. All rights reserved. 425 | Page


Essential Grid for ASP.NET MVC Classic

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Create a strongly typed view.
4. In the view, use the Model property in the Datasource() method to bind the data source.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)

© 2014 Syncfusion. All rights reserved. 426 | Page


Essential Grid for ASP.NET MVC Classic

.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})

%>

View[cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{

column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})

.Render();
}

© 2014 Syncfusion. All rights reserved. 427 | Page


Essential Grid for ASP.NET MVC Classic

5. Enable the editing mode by setting the edit mode to Normal and configure the editing
properties such as allow New, Allow Edit, and Allow Delete as displayed below:

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert
action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete
action.
})
%>

View[cshtml]

@( Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert
action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete
action.
})
)

Note: If you want to specify the URL in the AllowEdit property itself means, specify the
controller and the corresponding action name as a URL. If you using the Mappers property then
there is no need to specify the controller name.

6. Essential Grid allows editing and deleting records through grid unbound column items. In this
example, AddNew, Edit, Delete, Save, and Cancel buttons have been added in the toolbar
items. Therefore, configure the toolbar as displayed below:

© 2014 Syncfusion. All rights reserved. 428 | Page


Essential Grid for ASP.NET MVC Classic

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.column.Add("ManageRecords", col =>
{
// Unbound column for editing records.

col.Commands(cmd =>
{

cmd.Command(CommandTypes.Edit).Text("Edit").ImageUrl("/Content/Edit.png
").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptions.Imag
eOnly);
});
// Unbound column for updating records.

col.Commands(cmd =>
{

cmd.Command(CommandTypes.Update).Text("Update").ImageUrl("/Content/Upda
te.png").ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOpt
ions.ImagePlusText);
});
// Unbound column for deleting records.

col.Commands(cmd1 =>
{

cmd1.Command(CommandTypes.Delete).Text("Delete").ImageUrl("/Content/Del
ete.png").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptio
ns.TextOnly);
});
col.Commands(command =>
{

command.Command(CommandTypes.Custom)

.ItemType(UnBoundItemTypes.Button)

.ItemOption(UnboundItemOptions.TextOnly)

.Mapper("ViewDetails?Orderid={OrderID}")

.Text("View");
});
}).UnBound(true); // Unbound must be true
to make it an unbound column.

© 2014 Syncfusion. All rights reserved. 429 | Page


Essential Grid for ASP.NET MVC Classic

})
%>

View[cshtml]

@( Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.column.Add("ManageRecords", col =>
{
// Unbound column for editing records.

col.Commands(cmd =>
{

cmd.Command(CommandTypes.Edit).Text("Edit").ImageUrl("/Content/Edit.png
").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptions.Imag
eOnly);
});
// Unbound column for updating records.

col.Commands(cmd =>
{

cmd.Command(CommandTypes.Update).Text("Update").ImageUrl("/Content/Upda
te.png").ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOpt
ions.ImagePlusText);
});
// Unbound column for deleting records.

col.Commands(cmd1 =>
{

cmd1.Command(CommandTypes.Delete).Text("Delete").ImageUrl("/Content/Del
ete.png").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptio
ns.TextOnly);
});
col.Commands(command =>
{

command.Command(CommandTypes.Custom)

.ItemType(UnBoundItemTypes.Button)

.ItemOption(UnboundItemOptions.TextOnly)

.Mapper("ViewDetails?Orderid={OrderID}")

.Text("View");
});

© 2014 Syncfusion. All rights reserved. 430 | Page


Essential Grid for ASP.NET MVC Classic

}).UnBound(true); // Unbound must be true


to make it an unbound column.

})

Note: The Mapper action Command can be used in an unbound column for command type as
Custom only. If we define the mapper for defined commands like Edit, Save, Cancel, Insert there will
be unnecessary conflict between the grid mappers for editing actions and mapper defined for
commands. To avoid this type of conflict, use the Unbound Mapper action for Custom command
only.

7. Specify the primary property which uniquely identifies the grid record.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{

edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary key to


primary key collections.
})
%>

View[cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{

edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary key to


primary key collections.
})
.Render();
}

8. In the controller, create a method to add new records to grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.

Controller

/// <summary>
/// Used to insert the record into the database and refresh the grid.

© 2014 Syncfusion. All rights reserved. 431 | Page


Essential Grid for ASP.NET MVC Classic

/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

9. In the controller, create a method to save changes as displayed below.

In this example, the repository method Update() is used to update records to the data source.

Controller

/// Used to insert the record into database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data is displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update() is used to update the records in
the data source.
OrderRepository.Update(ord);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

10. In the controller, create a method to delete the records from the database as displayed
below.

© 2014 Syncfusion. All rights reserved. 432 | Page


Essential Grid for ASP.NET MVC Classic

In this example, the repository action Delete() will delete the record from the data source.

Controller

/// <summary>
/// Used to delete the records from the data source and refresh the
grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

11. In the controller, create a method to view the records from the database as displayed below.

In this example, the repository action ViewDetails() will show the record from the data source.

Controller

public ActionResult ViewDetails(int? Orderid)


{
var data = OrderRepository.GetAllRecords().Where(ord =>
ord.OrderID == Orderid).FirstOrDefault();
return Json(new { OrderDetails = data },
JsonRequestBehavior.AllowGet);
}

12. Run the application and click the Edit button to edit the record. The grid will appear as
displayed below.

© 2014 Syncfusion. All rights reserved. 433 | Page


Essential Grid for ASP.NET MVC Classic

Figure 146: Dialog Editing through Grid Builder

4.7.8.3.1.2 Through GridPropertiesModel


The steps to work with the editing feature through GridPropertiesModel are as follows.

1. Add the MicrosoftMvcValidation.debug.js file in the master page.

View[ASPX]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>

© 2014 Syncfusion. All rights reserved. 434 | Page


Essential Grid for ASP.NET MVC Classic

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-

© 2014 Syncfusion. All rights reserved. 435 | Page


Essential Grid for ASP.NET MVC Classic

ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Add the following code in the Index.aspx file to create the Grid control in the view.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1",

(GridPropertiesModel<EditableOrder>)ViewData["GridModel"])%>

View[cshtml]

@(Html.Syncfusion().Grid<EditableOrder>("Grid1",

(GridPropertiesModel<EditableOrder>)ViewData["GridModel"]))

4. Customize the unbound column as shown below:

[Controller]
GridCommands<EditableOrder> cmd1 = new GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Edit.png"),
ItemOption = UnboundItemOptions.ImageOnly,
Text = "Edit",
Type = "Edit"
};
GridCommands<EditableOrder> cmd2 = new
GridCommands<EditableOrder>()
{

© 2014 Syncfusion. All rights reserved. 436 | Page


Essential Grid for ASP.NET MVC Classic

ItemType = UnBoundItemTypes.HyperLink,
ImageUrl = Url.Content("~/Content/Images/Update.png"),
ItemOption = UnboundItemOptions.ImagePlusText,
Text = "Update",
Type = "Update"
};
GridCommands<EditableOrder> cmd3 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Delete.png"),
ItemOption = UnboundItemOptions.TextOnly,
Text = "Delete",
Type = "Delete"
};
GridCommands<EditableOrder> cmd4 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Delete.png"),
ItemOption = UnboundItemOptions.TextOnly,
Text = "View",
Type = "Custom",
Mapper = "ViewDetails?Orderid={OrderID}"
};
List<GridCommands<EditableOrder>> commandColl = new
List<GridCommands<EditableOrder>>();
commandColl.Add(cmd1);
commandColl.Add(cmd2);
commandColl.Add(cmd3);
commandColl.Add(cmd4);

Note: We can use Mapper action Command in unbound column for command type as Custom
only. If we define the mapper for defined commands like Edit, Save, Cancel, Insert there will be
unnecessary conflict between the grid mappers for editing actions and mapper defined for
commands. To avoid this type of conflicts we suggest you to use the Unbound Mapper action for
Custom command only.

5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()

© 2014 Syncfusion. All rights reserved. 437 | Page


Essential Grid for ASP.NET MVC Classic

{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Marble
};
model.Columns = new List<GridColumn<EditableOrder>>
{
new GridColumn<EditableOrder>
{

HeaderText = "Order ID",


MappingName = "OrderID",
ColumnType=typeof(int)
},
new GridColumn<EditableOrder>
{
HeaderText = "Customer ID",
MappingName = "CustomerID",
ColumnType=typeof(string)
},
new GridColumn<EditableOrder>
{
HeaderText = "Ship Country",
MappingName = "ShipCountry",
ColumnType=typeof(string)
},
new GridColumn<EditableOrder>
{
HeaderText = "Order Date",
MappingName = "OrderDate",
Format = "{OrderDate:MM/dd/yyyy}",
ColumnType=typeof(DateTime?)
},
new GridColumn<EditableOrder>
{
HeaderText = "Freight",
MappingName = "Freight",
ColumnType=typeof(decimal)
},
new GridColumn<EditableOrder>
{
IsUnbound = true,
MappingName = "Manage Records",
ColumnType=typeof(string),
Commands = commandColl
}
};
ViewData["GridModel"] = model;

© 2014 Syncfusion. All rights reserved. 438 | Page


Essential Grid for ASP.NET MVC Classic

6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AllowEdit and AllowDelete as displayed below.

Controller

// Create an object for grid editing and enable the edit, add
new, and delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true, AllowDelete =
true };
// Set the action mappers for the insert, delete, and save actions.
edit.DeleteMapper = "DeleteOrder";
edit.GridSaveMapper = "OrderSave";
edit.InsertMapper ="AddOrder";

7. Specify the GridEditMode through the EditMode property.

Controller
// Set the Edit mode.
edit.EditMode = GridEditMode.Normal;

8. Specify the primary property which uniquely identifies the grid record.

Controller
// Add the PrimaryKey value to uniquely identify the record.
edit.PrimaryKey = new List<string>() { "OrderID" };

9. Add the edit object to the model.

Controller
// Add the edit object to the model.
model.Editing = edit;

10. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.

© 2014 Syncfusion. All rights reserved. 439 | Page


Essential Grid for ASP.NET MVC Classic

Controller

/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

11. In the controller, create a method to save changes as displayed below.

In this example, the repository method Update() is used to update records to the data source:

Controller

/// Used to insert the record in the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the records into
datasource.
OrderRepository.Update(ord);
//After saving the records into datasource refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

12. In the controller, create a method to delete the records from the database as displayed
below.

© 2014 Syncfusion. All rights reserved. 440 | Page


Essential Grid for ASP.NET MVC Classic

In this example, the repository action Delete() will delete the record from the data source.

Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

13. In the controller, create a method to view the records from the database as displayed below.

In this example, the repository action ViewDetails() will show the record from the data source.
Controller

public ActionResult ViewDetails(int? Orderid)


{
var data = OrderRepository.GetAllRecords().Where(ord =>
ord.OrderID == Orderid).FirstOrDefault();
return Json(new { OrderDetails = data },
JsonRequestBehavior.AllowGet);
}

14. Run the application. The grid will appear as displayed below.

© 2014 Syncfusion. All rights reserved. 441 | Page


Essential Grid for ASP.NET MVC Classic

Figure 147: Unbound Column Editing through the GridPropertiesMode

4.7.8.3.2 JSON Mode

4.7.8.3.2.1 Through GridBuilder


The steps to work with the unbound column editing feature through GridBuilder are as follows:

1. Add the MicrosoftMvcValidation.debug.js file in the master page.

View[ASPX]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>

</head>

© 2014 Syncfusion. All rights reserved. 442 | Page


Essential Grid for ASP.NET MVC Classic

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>
60.

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-

© 2014 Syncfusion. All rights reserved. 443 | Page


Essential Grid for ASP.NET MVC Classic

ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Create a strongly typed view.
4. In the view, set the ActionMode as JSON.

View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})

%>

View[cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(column =>
{

column.Add(p =>
p.OrderID).HeaderText("Order ID");

© 2014 Syncfusion. All rights reserved. 444 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.ShipCountry).HeaderText("Ship
Country").CellEditType(CellEditType.DropdownEdit);
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{0:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight").Format("{0:C}");
column.Add(p =>
p.Delivered).HeaderText("Delivered");
})

.Render();
}

5. Enable the editing mode by setting the edit mode to Normal and configure the editing
properties such as AllowNew, AllowEdit, and AllowDelete as displayed below.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the
controller and action method which will perform the insert
action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete
action.
})
%>

View[cshtml]

@( Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{
edit.AllowEdit(true, "Home/OrderSave")// Specify
the controller and action method which will perform the update
action.
.AllowNew(true, "Home/AddOrder")// Specify the

© 2014 Syncfusion. All rights reserved. 445 | Page


Essential Grid for ASP.NET MVC Classic

controller and action method which will perform the insert


action.
.AllowDelete(true, "Home/DeleteOrder");// Specify
the controller and action method which will perform the delete
action.
})
)

Note: If you want to specify the URL in the AllowEdit property itself means, specify the
controller and the corresponding action name as a URL. If you using the Mappers property then
there is no need to specify the controller name.

6. Essential Grid allows editing and deleting records through grid unbound column items. In this
example, AddNew, Edit, Delete, Save, and Cancel buttons have been added in the toolbar
items. Therefore, configure the toolbar as displayed below.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.ActionMode(ActionMode.JSON)
.column.Add("ManageRecords", col =>
{
// Unbound column for editing records.

col.Commands(cmd =>
{

cmd.Command(CommandTypes.Edit).Text("Edit").ImageUrl("/Content/Edit.png
").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptions.Imag
eOnly);
});
// Unbound column for updating records.

col.Commands(cmd =>
{

cmd.Command(CommandTypes.Update).Text("Update").ImageUrl("/Content/Upda
te.png").ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOpt
ions.ImagePlusText);
});
// Unbound column for deleting records.

col.Commands(cmd1 =>
{

cmd1.Command(CommandTypes.Delete).Text("Delete").ImageUrl("/Content/Del
ete.png").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptio
ns.TextOnly);
});

© 2014 Syncfusion. All rights reserved. 446 | Page


Essential Grid for ASP.NET MVC Classic

col.Commands(command =>
{

command.Command(CommandTypes.Custom)

.ItemType(UnBoundItemTypes.Button)

.ItemOption(UnboundItemOptions.TextOnly)

.Mapper("ViewDetails?Orderid=${OrderID}")

.Text("View");
});

}).UnBound(true); // Unbound must be true


to make it as unbound column

})
%>

View[cshtml]

@( Html.Syncfusion().Grid<EditableOrder>("Grid1")
. ActionMode(ActionMode.JSON)

.column.Add("ManageRecords", col =>


{
// Unbound column for editing records.

col.Commands(cmd =>
{

cmd.Command(CommandTypes.Edit).Text("Edit").ImageUrl("/Content/Edit.png
").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptions.Imag
eOnly);
});
// Unbound column for updating records.

col.Commands(cmd =>
{

cmd.Command(CommandTypes.Update).Text("Update").ImageUrl("/Content/Upda
te.png").ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOpt
ions.ImagePlusText);
});
// Unbound column for deleting records.

© 2014 Syncfusion. All rights reserved. 447 | Page


Essential Grid for ASP.NET MVC Classic

col.Commands(cmd1 =>
{

cmd1.Command(CommandTypes.Delete).Text("Delete").ImageUrl("/Content/Del
ete.png").ItemType(UnBoundItemTypes.Button).ItemOption(UnboundItemOptio
ns.TextOnly);
});
col.Commands(command =>
{

command.Command(CommandTypes.Custom)

.ItemType(UnBoundItemTypes.Button)

.ItemOption(UnboundItemOptions.TextOnly)

.Mapper("ViewDetails?Orderid=${OrderID}")

.Text("View");
});
}).UnBound(true); // Unbound must be true
to make it as unbound column

})

Note: The Mapper action Command in can be used in unbound columns for command
type as Custom only. If we define the mapper for defined commands like Edit, Save,
Cancel, and Insert there will be an unnecessary conflict between the grid mappers for
editing actions and mapper defined for commands. To avoid this type of conflicts we
suggest you to use the Unbound Mapper action for Custom command only.

7. Specify the primary property which uniquely identifies the grid record.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{

edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary key to


primary key collections.
})
%>

© 2014 Syncfusion. All rights reserved. 448 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Editing( edit=>{

edit.PrimaryKey(key => key.Add(p => p.OrderID)); // Add primary key to


primary key collections.
})
.Render();
}

8. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer the repository action method displayed below.

Controller

/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

9. In the controller, create a method to save changes as displayed below.

In this example, the repository method Update() is used to update records to the data source.

Controller

/// Used to insert the record into database and refresh the grid.
/// </summary>

© 2014 Syncfusion. All rights reserved. 449 | Page


Essential Grid for ASP.NET MVC Classic

/// <param name="ord">Editable order.</param>


/// <returns>HtmlActionResult returns the data is displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update() is used to update the records in
the data source.
OrderRepository.Update(ord);
// After saving the records to the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

10. In the controller, create a method to delete the records from the database as displayed
below.

In this example, the repository action Delete() will delete the record from the data source.

Controller

/// <summary>
/// Used to delete the records from the data source and refresh the
grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

11. In the controller, create a method to View the records from the database as displayed
below.

In this example, the repository action ViewDetails() will show the record from the data source.
Controller

public ActionResult ViewDetails(int? Orderid)

© 2014 Syncfusion. All rights reserved. 450 | Page


Essential Grid for ASP.NET MVC Classic

{
var data = OrderRepository.GetAllRecords().Where(ord =>
ord.OrderID == Orderid).FirstOrDefault();
return Json(new { OrderDetails = data },
JsonRequestBehavior.AllowGet);
}

12. Run the application and click the Edit button to edit the record. The grid will appear as
displayed below.

Figure 148: Dialog Edit through Grid Builder

4.7.8.3.2.2 Through GridPropertiesModel


The steps to work with the editing feature through GridPropertiesModel are as follows.

1. Add the MicrosoftMvcValidation.debug.js file in the master page.

© 2014 Syncfusion. All rights reserved. 451 | Page


Essential Grid for ASP.NET MVC Classic

View[ASPX]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………
<script src="<%=
Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js") %>"
type="text/javascript"></script>
</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent" runat="server"
/></title>
………

<script
src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js ")"
type="text/javascript"></script>

</head>
61.

Note: Add the following script files when the UnobtrusiveJavaScriptEnabled is true in the
web.config file.
[Web.config]

<configuration>
<appSettings>
<add key='UnobtrusiveJavaScriptEnabled' value='true'/>
</appSettings>

[_Layout.cshtml]

<head>

. . . .
. . . .
<script src="@Url.Content("~/Scripts/jquery.unobtrusive-ajax.min.js")"
type="text/javascript"></script>

© 2014 Syncfusion. All rights reserved. 452 | Page


Essential Grid for ASP.NET MVC Classic

<script src="@Url.Content("~/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>
</head>

[Site.Master]

<head runat="server">
. . . .
. . . .
<script src="<%=Url.Content("~/Scripts/jquery.unobtrusive-
ajax.min.js")%>" type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/jquery.validate.min.js")%>"
type="text/javascript"></script>
<script
src="<%=Url.Content("~/Scripts/jquery.validate.unobtrusive.min.js")%
>" type="text/javascript"></script>
</head>

2. Create a model in the application.


3. Add the following code in the Index.aspx file to create the Grid control in the view.

View[ASPX]

<%= Html.Syncfusion().Grid<EditableOrder>("Grid1",

(GridPropertiesModel<EditableOrder>)ViewData["GridModel"])
})%>

View[cshtml]

@( Html.Syncfusion().Grid<EditableOrder>("Grid1",

(GridPropertiesModel<EditableOrder>)ViewData["GridModel"]))

4. Customize the unbound column as shown below.

© 2014 Syncfusion. All rights reserved. 453 | Page


Essential Grid for ASP.NET MVC Classic

[Controller]
GridCommands<EditableOrder> cmd1 = new GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Edit.png"),
ItemOption = UnboundItemOptions.ImageOnly,
Text = "Edit",
Type = "Edit"
};
GridCommands<EditableOrder> cmd2 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.HyperLink,
ImageUrl = Url.Content("~/Content/Images/Update.png"),
ItemOption = UnboundItemOptions.ImagePlusText,
Text = "Update",
Type = "Update"
};
GridCommands<EditableOrder> cmd3 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Delete.png"),
ItemOption = UnboundItemOptions.TextOnly,
Text = "Delete",
Type = "Delete"
};
GridCommands<EditableOrder> cmd4 = new
GridCommands<EditableOrder>()
{
ItemType = UnBoundItemTypes.Button,
ImageUrl = Url.Content("~/Content/Images/Delete.png"),
ItemOption = UnboundItemOptions.TextOnly,
Text = "View",
Type = "Custom",
Mapper = "ViewDetails?Orderid={OrderID}"
};
List<GridCommands<EditableOrder>> commandColl = new
List<GridCommands<EditableOrder>>();
commandColl.Add(cmd1);
commandColl.Add(cmd2);
commandColl.Add(cmd3);
commandColl.Add(cmd4);

© 2014 Syncfusion. All rights reserved. 454 | Page


Essential Grid for ASP.NET MVC Classic

Note: We can use Mapper action Command in unbound column for command type as Custom
only. If we define the mapper for defined commands like Edit, Save, Cancel, Insert there will be
unnecessary conflict between the grid mappers for editing actions and mapper defined for
commands. To avoid this type of conflicts we suggest you to use the Unbound Mapper action for
Custom command only.

5. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.

Controller

GridPropertiesModel<EditableOrder> model = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
Caption = "Orders",
ActionMode = ActionMode.JSON,

AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
AutoFormat=Skins.Marble
};
model.Columns = new List<GridColumn<EditableOrder>>
{
new GridColumn<EditableOrder>
{

HeaderText = "Order ID",


MappingName = "OrderID",
ColumnType=typeof(int)
},
new GridColumn<EditableOrder>
{
HeaderText = "Customer ID",
MappingName = "CustomerID",
ColumnType=typeof(string)
},
new GridColumn<EditableOrder>
{
HeaderText = "Ship Country",
MappingName = "ShipCountry",
ColumnType=typeof(string)
},
new GridColumn<EditableOrder>
{
HeaderText = "Order Date",
MappingName = "OrderDate",
Format = "{OrderDate:MM/dd/yyyy}",

© 2014 Syncfusion. All rights reserved. 455 | Page


Essential Grid for ASP.NET MVC Classic

ColumnType=typeof(DateTime?)
},
new GridColumn<EditableOrder>
{
HeaderText = "Freight",
MappingName = "Freight",
ColumnType=typeof(decimal)
},
new GridColumn<EditableOrder>
{
IsUnbound = true,
MappingName = "Manage Records",
ColumnType=typeof(string),
Commands = commandColl
}
};

ViewData["GridModel"] = model;

6. Enable editing by using the Editing property in the GridPropertiesModel and configure the
editing properties such as AddNew, AllowEdit, and AllowDelete as displayed below.

Controller

// Create an object for grid editing and enable the edit, add
new, and delete actions.
GridEditing edit = new GridEditing() { AllowEdit = true, AllowDelete =
true };
// Set the action mappers for the insert, delete, and save actions.
edit.DeleteMapper = "DeleteOrder";
edit.GridSaveMapper = "OrderSave";
edit.InsertAction = "AddOrder";

7. Specify the GridEditMode through the EditMode property.

Controller

// Set the Edit mode.


edit.EditMode = GridEditMode.Normal;

8. Specify the primary property which uniquely identifies the grid record.

Controller

© 2014 Syncfusion. All rights reserved. 456 | Page


Essential Grid for ASP.NET MVC Classic

// Add the PrimaryKey value to uniquely identify the record.


edit.PrimaryKey = new List<string>() { "OrderID" };

9. Add the edit object to the model.

Controller

// Add the edit object to the model.


model.Editing = edit;

10. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.

Controller

/// <summary>
/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add() is used to insert records in the data
source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

11. In the controller, create a method to save changes as displayed below.

In this example, the repository method Update() is used to update records to the data source:

Controller

/// Used to insert the record in the database and refresh the grid.

© 2014 Syncfusion. All rights reserved. 457 | Page


Essential Grid for ASP.NET MVC Classic

/// </summary>
/// <param name="ord">Editable order.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the records into
datasource.
OrderRepository.Update(ord);
//After saving the records into datasource refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

12. In the controller, create a method to delete the records from the database as displayed
below.

In this example, the repository action Delete() will delete the record from the data source.

Controller

/// <summary>
/// Used to delete records from the data source and refresh the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed in the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repoistory action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

13. In the controller, create a method to View the records from the database as displayed
below.

In this example, the repository action ViewDetails() will show the record from the data source.
Controller

public ActionResult ViewDetails(int? Orderid)

© 2014 Syncfusion. All rights reserved. 458 | Page


Essential Grid for ASP.NET MVC Classic

{
var data = OrderRepository.GetAllRecords().Where(ord =>
ord.OrderID == Orderid).FirstOrDefault();
return Json(new { OrderDetails = data },
JsonRequestBehavior.AllowGet);
}

14. Run the application. The grid will appear as displayed below.

Figure 149: Dialog Editing through the GridPropertiesModel

4.7.9 Editable and Repository class details


EditableOrder Class
Controller
/// <summary>
/// EditableOrder Model.
/// </summary>

© 2014 Syncfusion. All rights reserved. 459 | Page


Essential Grid for ASP.NET MVC Classic

public class EditableOrder


{
[Required(ErrorMessage = "Order ID is required.")]
public int OrderID
{
get;
set;
}

[StringLength(5, ErrorMessage = "Customer ID must be 5


characters.")]
public string CustomerID
{
get;
set;
}

[Range(1, 9, ErrorMessage = "EmployeeID must be between 0 and


9.")]
public int? EmployeeID
{
get;
set;
}

public DateTime? OrderDate


{
get;
set;
}

public string ShipName


{
get;
set;
}

[StringLength(15, ErrorMessage = "ShipCity must be 15


characters.")]
public string ShipCity
{
get;
set;
}

public string ShipAddress


{
get;
set;

© 2014 Syncfusion. All rights reserved. 460 | Page


Essential Grid for ASP.NET MVC Classic

public string ShipRegion


{
get;
set;
}

public string ShipPostalCode


{
get;
set;
}

[StringLength(15, ErrorMessage = "ShipName must be 15


characters.")]
public string ShipCountry
{
get;
set;
}

[Range(1.00, 1000.00, ErrorMessage = "Freight must be between


1.00 & 1000")]
public decimal? Freight
{
get;
set;
}
}

4.7.9.2 OrderRepository Class

public static class OrderRepository


{
/// <summary>
/// Used to get all records from northwind database and
converts into EditableDatasource.
/// </summary>
/// <returns>List of EditableOrder</returns>
public static IList<EditableOrder> GetAllRecords()
{
IList<EditableOrder> orders =
(IList<EditableOrder>)HttpContext.Current.Session["Orders"];

if (orders == null)
{
HttpContext.Current.Session["Orders"] = orders = (from

© 2014 Syncfusion. All rights reserved. 461 | Page


Essential Grid for ASP.NET MVC Classic

ord in new NorthwindDataContext().Orders.Take(50)


select new EditableOrder
{
OrderID = ord.OrderID,
OrderDate = ord.OrderDate,
CustomerID = ord.CustomerID,
EmployeeID = ord.EmployeeID,
Freight = ord.Freight,
ShipAddress = ord.ShipAddress,
ShipCity = ord.ShipCity,
ShipName = ord.ShipName,
ShipPostalCode = ord.ShipPostalCode,
ShipRegion = ord.ShipRegion,
ShipCountry = ord.ShipCountry
}).ToList();
}
return orders;
}

/// <summary>
/// Used for add the new Editable order to datasource.
/// </summary>
/// <param name="order">EditableOrder</param>
public static void Add(EditableOrder order)
{
GetAllRecords().Insert(0, order);
}

/// <summary>
/// Used to find the order from the datasource.
/// </summary>
/// <param name="OrderID">OrderID</param>
/// <returns>EditableOrder as result</returns>
public static EditableOrder Select(int? OrderID)
{

EditableOrder result = GetAllRecords().Where(o => o.OrderID


== OrderID).FirstOrDefault();

return result;
}

/// <summary>
/// Used to delete the EditableOrder from datasource using
OrderID.
/// </summary>
/// <param name="OrderID">OrderID</param>
public static void Delete(int OrderID)
{
EditableOrder result = GetAllRecords().Where(o => o.OrderID
== OrderID).FirstOrDefault();

© 2014 Syncfusion. All rights reserved. 462 | Page


Essential Grid for ASP.NET MVC Classic

GetAllRecords().Remove(result);
}

/// <summary>
/// Used to update the changes to datasource.
/// </summary>
/// <param name="order"></param>
public static void Update(EditableOrder order)
{
EditableOrder result = GetAllRecords().Where(o => o.OrderID
== order.OrderID).FirstOrDefault();
if (result != null)
{
result.OrderID = order.OrderID;
result.CustomerID = order.CustomerID;
result.EmployeeID = order.EmployeeID;
result.OrderDate = order.OrderDate;
result.ShipAddress = order.ShipAddress;
result.ShipCity = order.ShipCity;
result.ShipCountry = order.ShipCountry;
result.ShipName = order.ShipName;
result.ShipRegion = order.ShipRegion;
result.ShipPostalCode = order.ShipPostalCode;
result.Freight = order.Freight;
}
}
}

4.7.9.3 JSONOrder Class

namespace MvcSampleApplication.Models
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

/// <summary>
/// JSON mode order class.
/// </summary>
public class JSONOrder
{
public int OrderID
{
get;
set;
}

© 2014 Syncfusion. All rights reserved. 463 | Page


Essential Grid for ASP.NET MVC Classic

public DateTime? OrderDate


{
get;
set;
}

public int? EmployeeID


{
get;
set;
}

public string CustomerID


{
get;
set;
}

public string ShipCountry


{
get;
set;
}

public string ShipCity


{
get;
set;
}
}
}

4.7.9.4 AutoFormatting Class

public class AutoFormatting


{

public AutoFormatting(DateTime date, decimal currency, int


number, int telephone)
{
this.Dates = date;
this.Currency = currency;
this.Number = number;
this.Telephone = telephone;
}

public decimal Currency


{
get;
set;
}

© 2014 Syncfusion. All rights reserved. 464 | Page


Essential Grid for ASP.NET MVC Classic

public DateTime Dates


{
get;
set;
}

public int Number


{
get;
set;
}

public int Telephone


{
get;
set;
}
}

4.7.9.5 AutoFormatting Repository

public static class AutoFormatRepository


{
/// <summary>
/// Get all AutoFormatting data.
/// </summary>
/// <returns></returns>
public static IList<AutoFormatting> GetData()
{
List<AutoFormatting> result = new List<AutoFormatting>();
result.Add(new
AutoFormatting(Convert.ToDateTime("10/10/2005 6:30AM"), 15123.45m,
1362, 458792658));
result.Add(new AutoFormatting(Convert.ToDateTime("10/9/2006
7:20PM"), 12893.45m, 234, 254879362));
result.Add(new AutoFormatting(Convert.ToDateTime("9/10/2007
8:45AM"), 45123.45m, 1298, 569786269));
result.Add(new AutoFormatting(Convert.ToDateTime("5/10/2004
7:45PM"), 67189.45m, 3362, 163840382));
result.Add(new AutoFormatting(Convert.ToDateTime("2/3/2009
5:34AM"), 23190.45m, 1839, 983729405));
result.Add(new AutoFormatting(Convert.ToDateTime("6/8/2020
9:56PM"), 43145.45m, 89982, 937292033));
result.Add(new AutoFormatting(Convert.ToDateTime("3/2/2001
1:45AM"), 5198.45m, 6739, 473920219));
result.Add(new AutoFormatting(Convert.ToDateTime("2/1/2003
2:23PM"), 345123.45m, 2262, 987654321));
result.Add(new
AutoFormatting(Convert.ToDateTime("11/12/2005 9:56PM"), 315123.45m,

© 2014 Syncfusion. All rights reserved. 465 | Page


Essential Grid for ASP.NET MVC Classic

48393, 123456789));

return result;

}
}

4.7.9.6 OrderDetailEdit Class

/// <summary>
/// OrderDetailEdit Model.
/// </summary>
public partial class OrderDetailEdit
{
[Required(ErrorMessage = "Order ID is required.")]
public int OrderID
{
get;
set;
}
[Required(ErrorMessage = "Product ID is required.")]
public int ProductID
{
get;
set;
}
[Required(ErrorMessage = "Quantity is required.")]
public Int16 Quantity
{
get;
set;
}
public Decimal UnitPrice
{
get;
set;
}
public Single Discount
{
get;
set;
}
}

4.7.9.7 OrderDetailRepository
public static class OrderDetailRepository
{
public static IList<OrderDetailEdit> GetAllRecords(int? OrderID

© 2014 Syncfusion. All rights reserved. 466 | Page


Essential Grid for ASP.NET MVC Classic

)
{
IList<OrderDetailEdit> ordersdetails;
ordersdetails = (IList<OrderDetailEdit>)HttpContext.Current
.Session["childgridGlobal"];
if (ordersdetails == null)
{
HttpContext.Current.Session["childgridGlobal"] = orders
details = (from ord in new NorthwindDataContext().Order_Details//.Take(
200)
select new OrderDetailE
dit
{
OrderID = ord.Order
ID,
ProductID = ord.Pro
ductID,
UnitPrice = ord.Uni
tPrice,
Quantity = ord.Quan
tity,
Discount = ord.Disc
ount
}).ToList();
}
if(OrderID != null)
ordersdetails = ordersdetails.Where(o => o.OrderID == O
rderID).ToList();
return ordersdetails;
}
public static void Delete(int? Orderid, int Productid)
{
OrderDetailEdit result = GetAllRecords(Orderid).Where(o =>
o.ProductID == Productid).FirstOrDefault();
GetAllRecords(Orderid).Remove(result);
}
public static OrderDetailEdit Select(int? OrderID)
{

OrderDetailEdit result = GetAllRecords(OrderID).Where(o =>


o.OrderID == OrderID).FirstOrDefault();

return result;
}
public static void Update(OrderDetailEdit order)
{
OrderDetailEdit result = GetAllRecords(order.OrderID).Where
(o => o.ProductID == order.ProductID).FirstOrDefault();
if (result != null)
{
result.OrderID = order.OrderID;
result.ProductID = order.ProductID;
result.UnitPrice = order.UnitPrice;
result.Quantity = order.Quantity;

© 2014 Syncfusion. All rights reserved. 467 | Page


Essential Grid for ASP.NET MVC Classic

result.Discount = order.Discount;
}
}
}

4.8 Exporting
4.8.1 Excel Export
Export to Excel is one of the most common functionalities that is required in .NET. The Essential
Grid Control has in-built support for Excel Export. You can download data from the Grid control to
an Excel spreadsheet for offline verification and/or computation. This can be achieved by using
the GridExcelExportActionResult<T> extension. This extension applies the Grid control's styles
and formats to Excel. The GridExcelExportActionResult<T> is derived from
GridActionResultBase<T>. The XlsIO libraries are used to support the conversion of the Grid
contents to Excel.
All the content from a Grid can be converted to an Excel Spreadsheet. It also provides the option
to specify the version of the Excel file by using the ExcelVersion enum. The versions that can be
specified are as follows:
 ExcelVersion.Excel97to2003
 ExcelVersion.Excel2007
 ExcelVersion.Excel2010

Properties

Property Descriptio Type Value it Property Syntax


n of Accepts
proper
ty
FileName Gets or sets String Any string var data = new
the Excel file value. NorthwindDataContext().Orders.Ta
name. ke(200).ToList();

return
data.GridExportToExcel<Order>("
GridExcel.xlsx",
ExcelVersion.Excel2007);

ExcelVersio Gets or sets Enum ExcelVersion.E var data = new


n the Excel xcel97to2003 NorthwindDataContext().Orders.Ta
version for ExcelVersion.E ke(200).ToList();
the Excel file. xcel2007
return
ExcelVersion.E data.GridExportToExcel<Order>("

© 2014 Syncfusion. All rights reserved. 468 | Page


Essential Grid for ASP.NET MVC Classic

xcel2010 GridExcel.xlsx",
ExcelVersion.Excel2007);

Methods

Name Parameters Return type Description


GridExportToExcel ExcelFileName, ActionResult Used to export the grid
ExcelVersion content to the Excel
(IEnumerable<T>)
format.

Export(GridToolbarItem,mapper) GridToolbarItem, IToolBarBuilder Used to add the


Mapper GridExcel toolbar button
and the Excel export
action mapper.

Export(GridToolbarItem, GridToolBarItem, IToolBarBuilder Used to add the


Caption, mapper) Caption, Mapper GridExcel toolbar button
with the caption and the
action mapper.

The Excel exporting feature can be enabled through two ways:


 GridBuilder
 GridPropertiesModel

4.8.1.1 Through GridBuilder

The steps to enable the Excel exporting feature through GridBuilder are as follows:
1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property in the Datasource(), to bind the data source.

62.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order

© 2014 Syncfusion. All rights reserved. 469 | Page


Essential Grid for ASP.NET MVC Classic

Date").Format("{0:dddd, MMMM d, yyyy}");


column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
%>

63.
View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Render();
}

4. Configure the grid toolbar to enable exporting grid records.

© 2014 Syncfusion. All rights reserved. 470 | Page


Essential Grid for ASP.NET MVC Classic

64.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.ToolBar(tools =>
tools.Export(GridToolBarItems.ExcelExport, "Export",
"ExportToExcel"))
%>

65.
View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.ToolBar(tools =>
tools.Export(GridToolBarItems.ExcelExport, "Export",
"ExportToExcel")).Render();
}

5. Specify the file name and Excel version details in the ExportToExcel() method.

Controller

/// <summary>
/// Used to export the grid as an Excel file.
/// </summary>
/// <param name="grid">Grid object.</param>
/// <returns>Excel file.</returns>
public ActionResult ExportToExcel()
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToExcel<Order>("GridExcel.xlsx",
ExcelVersion.Excel2007);
}

6. Run the application and click the Export button. The grid will appear as displayed
below.

© 2014 Syncfusion. All rights reserved. 471 | Page


Essential Grid for ASP.NET MVC Classic

Figure 150: Exported Grid Content

4.8.1.2 Through GridPropertiesModel

1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).

© 2014 Syncfusion. All rights reserved. 472 | Page


Essential Grid for ASP.NET MVC Classic

3. Add the following code in the Index.aspx file to create the Grid control in the view.
66.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel", column=> {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel", column=> {
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
}))

© 2014 Syncfusion. All rights reserved. 473 | Page


Essential Grid for ASP.NET MVC Classic

4. Create a GridPropertiesModel in the Index method and the assign grid properties in
the model.

Controller

GridPropertiesModel<Order> model = new


GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200),
Caption = "Product",
AllowPaging = true,
AllowSorting = true
};

5. Configure the GridPropertiesModel as displayed below, to accept the ExcelExport


ActionMapper and to render the toolbar.
67.
Controller
ToolbarSettings toolbar = new ToolbarSettings();
toolbar.Enable = true; // Used to enable the toolbar.
// Add the Excel tool item in the toolbar with caption and
mapper name.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.ExcelExport, Mapper = "ExportToExcel"});
model.ToolBar = toolbar;

Note: The syntax for the ExcelExport item is toolbarcaption + ~ +mapperName. In this example,
Export is the caption and ExcelToExcel is the name of the mapper.

6. Pass the GridPropertiesModel to the view by using ViewData.


68.
Controller

ViewData["GridModel"] = model;

7. Specify the file name and the Excel version details in the ExportToExcel() method.

Controller

© 2014 Syncfusion. All rights reserved. 474 | Page


Essential Grid for ASP.NET MVC Classic

/// <summary>
/// Used to export the grid as an Excel worksheet.
/// </summary>
/// <param name="grid">Grid object.</param>
/// <returns>Excel file.</returns>
public ActionResult ExportToExcel()
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToExcel<Order>("GridExcel.xlsx",
ExcelVersion.Excel2007);
}

8. Run the application and click the Export button. The grid will appear as displayed
below.

© 2014 Syncfusion. All rights reserved. 475 | Page


Essential Grid for ASP.NET MVC Classic

Figure 151: Exported Grid Content

4.8.1.3 Exporting through Custom Buttons

The steps to export through custom buttons are as follows:


1. Create a model in the application. Refer to How to>Adding a model to the Application.

© 2014 Syncfusion. All rights reserved. 476 | Page


Essential Grid for ASP.NET MVC Classic

2. Create a strongly typed view. Refer to How to>Strongly Typed View.


3. In the view, use the Model property in the DataSource to bind the data source.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");

© 2014 Syncfusion. All rights reserved. 477 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(c =>
c.ShipPostalCode).HeaderText("Ship postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
})
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Render();
}

4. Create a button element in the view page and write the code displayed below for the
button click event.
69.
<script type="text/javascript">
$(document).ready(function () {
$("#export").bind('click', function () {
// Find the gridobject;
var gridObj = $find("OrdersGrid");
// Set the ExcelExport action mapper using
Set_ExcelExportMapper().

gridObj.set_ExcelExportMapper("ExportToExcel");

// Call the SendExcelExportRequest().


gridObj.sendExcelExportRequest();
});
});

</script>

5. Specify the file name and Excel version details in the ExportToExcel() method.

Controller

/// <summary>
/// Used to export the grid as an Excel worksheet.
/// </summary>
/// <param name="grid">Grid object.</param>
/// <returns>Excel file.</returns>
public ActionResult ExportToExcel()
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToExcel<Order>("GridExcel.xlsx",
ExcelVersion.Excel2007);
}

© 2014 Syncfusion. All rights reserved. 478 | Page


Essential Grid for ASP.NET MVC Classic

6. Run the application and click the Export button. The grid will appear as displayed
below.

Figure 152: Exported Grid Content


Sample Link

© 2014 Syncfusion. All rights reserved. 479 | Page


Essential Grid for ASP.NET MVC Classic

To view the samples, follow the steps below:


1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Exporting > Export

4.8.2 PDF Export


You can export grid data to a PDF format using this feature, and can customize the exported grid
in any way that you might require.
Exporting is done through the server-side Export method.

Use Case Scenarios


Users can:
 Export grouped tables.
 Export nested tables.
 Export a grid with a multi-row record.
 Export summary rows.
 Export the styles applied to the grid can to a Word/PDF file.
 Export his or her choice of grid contents— i.e. visible or all.

4.8.2.1 Appearance and Structure of PDF Export


The following figures provide a basic idea of the appearance and structure of the feature.
This feature allows you to export normal and nested grids to PDF formats, as you can see in the
following screenshots:

© 2014 Syncfusion. All rights reserved. 480 | Page


Essential Grid for ASP.NET MVC Classic

Figure 153: Normal Grid in PDF

© 2014 Syncfusion. All rights reserved. 481 | Page


Essential Grid for ASP.NET MVC Classic

Figure 154: Hierarchical (Nested) Grid in PDF

© 2014 Syncfusion. All rights reserved. 482 | Page


Essential Grid for ASP.NET MVC Classic

4.8.2.2 Adding PDF Export Support to MVC Grid


The Grid-to-PDF and Grid-to-Word export support can be implemented in Essential Grid for MVC
using code as shown in the following sections:

4.8.2.2.1 Through GridBuilder


The steps to enable the PDF exporting feature through GridBuilder are as follows:
1. Create a model in the application.
2. Create a strongly typed view.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Configure the grid toolbar and add a mapper to enable exporting grid records.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
---------------
---------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.PDFExport,"PDF
Export");
})

.Mappers(map =>
{
map.ExportPdfAction("ExportToPDF");
})
%>

View[cshtml]

@ { Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
---------------
---------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.PDFExport,"PDF
Export");
})

.Mappers(map =>
{
map.ExportPdfAction("ExportToPDF");
}).Render();
}

© 2014 Syncfusion. All rights reserved. 483 | Page


Essential Grid for ASP.NET MVC Classic

5. Set its data source and render the view.


Controller

public ActionResult Index()


{
var data = new NorthwindDataContext
().Orders.Take(200).ToList();
return View(data);
}

6. Specify the file name, PDF version, and export option details in the GridExportToPDF()
method.

Controller

public ActionResult ExportToPDF(PagingParams args)


{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToPDF<Order>("GridPDF.pdf",
PdfVersion.Version1_7, args.ExportOption);
}

4.8.2.2.2 Through GridPropertiesModel

1. Create a model in the application.


2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code to the view.
View[ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>


{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship

© 2014 Syncfusion. All rights reserved. 484 | Page


Essential Grid for ASP.NET MVC Classic

City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
%>

View[cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>


{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
}).Render();
}

4. Create a GridPropertiesModel and the assign grid properties in the model.


70.
Controller

GridPropertiesModel <Order> model = new GridPropertiesModel


<Order>()
{
DataSource = new NorthwindDataContext().Orders.Take(200),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true
};

5. Configure the GridPropertiesModel as displayed below, to accept the PDFExport


ActionMapper and to render the toolbar.

© 2014 Syncfusion. All rights reserved. 485 | Page


Essential Grid for ASP.NET MVC Classic

Controller

ToolbarSettings toolbar = new ToolbarSettings ();


toolbar.Enable = true; // Used to enable the toolbar.
// Add the Excel toolbar item in the toolbar with a caption and mapper
name.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.ExcelExport, Mapper = "ExportToPDF"});
model.ToolBar = toolbar;

6. Specify the file name, PDF version, export option details in the GridExportToPDF()
method.

Controller
public ActionResult ExportToPDF(PagingParams args)
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToPDF<Order>("GridPDF.pdf",
PdfVersion.Version1_7, args.ExportOption);
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Exporting > Export

4.8.3 Word Export


This feature is very similar to PDF Export. Only the properties, methods, and events used.
differentiates this feature from that.
Use Case Scenarios
The user can:
 Export grouped tables.
 Export nested tables.
 Export a grid with a multi-row record.
 Export summary rows.
 Export the styles applied to the grid to the Word/PDF file.
 Export his or her choice of grid contents—i.e. visible or all.

4.8.3.1 Appearance and Structure of the Word Export


The following figures give you a basic idea of the appearance and structure of the feature.

© 2014 Syncfusion. All rights reserved. 486 | Page


Essential Grid for ASP.NET MVC Classic

This feature allows you to export normal and nested grids to Word formats, as you can see in the
screenshots below:

Figure 155: Normal Grid in Word

© 2014 Syncfusion. All rights reserved. 487 | Page


Essential Grid for ASP.NET MVC Classic

Figure 156: Hierarchical Grid in Word

© 2014 Syncfusion. All rights reserved. 488 | Page


Essential Grid for ASP.NET MVC Classic

Using this feature, you can export the grid to Word and PDF formats, and can format the cells of
the exported grid.
This feature supports the export of both normal and nested (hierarchical) grids as well.

4.8.3.2 Adding Word Export to MVC Grid

4.8.3.2.1 Through GridBuilder


The steps to enable the Word exporting feature through GridBuilder are as follows:
1. Create a model in the application.
2. Create a strongly typed view.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Configure the grid toolbar and add a mapper to enable grid record exporting.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
----------------
----------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.WordExport,"Word
Export");
})

.Mappers(map =>
{
map. ExportWordAction("ExportToWord");
})
%>

View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
----------------
----------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.WordExport,"Word
Export");
})

.Mappers(map =>

© 2014 Syncfusion. All rights reserved. 489 | Page


Essential Grid for ASP.NET MVC Classic

{
map. ExportWordAction("ExportToWord");
}).Render();
}

5. Set its data source and render the view.


71.
Controller

public ActionResult Index()


{
var data = new NorthwindDataContext
().Orders.Take(200).ToList();
return View(data);
}

6. Specify the file name and document version details in the GridExportToWord() method.

Controller
public ActionResult ExportToWord(PagingParams args)
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToWord<Order>("GridWord.doc",
DocumentVersion.Word2007, args.ExportOption);
}

4.8.3.2.2 Through GridPropertiesModel

1. Create a model in the application.


2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code to the view.

72.
View[cshtml]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>


{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");

© 2014 Syncfusion. All rights reserved. 490 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(c => c.CustomerID).HeaderText("Customer


ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
%>

View[cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>


{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
}).Render();;

4. Create a GridPropertiesModel and assign the grid properties in the model.


Controller

GridPropertiesModel <Order> model = new GridPropertiesModel


<Order>()
{
DataSource = new NorthwindDataContext().Orders.Take(200),
Caption = "Orders",
AllowPaging = true,

© 2014 Syncfusion. All rights reserved. 491 | Page


Essential Grid for ASP.NET MVC Classic

AllowSorting = true
};

5. Configure the GridPropertiesModel as displayed below to accept the WordExport


,ActionMapper and to render the toolbar.
Controller

ToolbarSettings toolbar = new ToolbarSettings ();


toolbar.Enable = true; // Used to enable the toolbar.
// Add the Word toolbar item to the toolbar with a caption and mapper
name.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.ExcelExport, Mapper = "ExportToWord"});
model.ToolBar = toolbar;

6. Specify the file name, PDF version, and export option details in the GridExportToWord()
method.

Controller

public ActionResult ExportToWord(PagingParams args)


{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridExportToWord<Order>("GridWord.doc",
DocumentVersion.Word2007, args.ExportOption);
}
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Exporting > Export

4.8.4 Properties
Exporting Grid to PDF and Word are two different actions that require slightly different properties,
methods, and events.
Properties to be used for PDF Export

Type of
Property Description Value it accepts Dependencies
property

© 2014 Syncfusion. All rights reserved. 492 | Page


Essential Grid for ASP.NET MVC Classic

Type of
Property Description Value it accepts Dependencies
property
Returns the
name of the
FileName String Any type of String NA
exported PDF
file

PdfVersion.Version1_1
PdfVersion.Version1_2
PdfVersion.Version1_3
Gets or sets
PdfVersion the version of PdfVersion.Version1_4
PdfVersion NA
the PDF PdfVersion.Version1_5
Document
PdfVersion.Version1_6
PdfVersion.Version1_7

All
Returns the
ConverterOptionsExt exporting Enum Visible NA
options

Specifies
whether True
ExportNestedTables nested tables bool NA
can be False
exported

Specifies
whether you True
UseAutoFormat can use the in- bool NA
built styles for False
Grid

Properties to be used for Word Export

Dependenci
Property Description Type of property Value it accepts
es

© 2014 Syncfusion. All rights reserved. 493 | Page


Essential Grid for ASP.NET MVC Classic

Returns the name of the


FileName String Any type of String NA
exported PDF file

DocumentVersion.Word2000
DocumentVersion.Word2002
WordVersion Gets or sets the version
DocumentVersion DocumentVersion.Word2003 NA
of the Word Document
DocumentVersion.Word2007

All
ConverterOptions Returns the exporting
Enum Visible NA
Ext options

ExportNestedTabl Specifies whether nested True


bool NA
es tables can be exported False

Specifies whether you True


UseAutoFormat can use the in-built styles bool NA
for Grid False

4.8.5 Methods
The methods used for both Grid to PDF and Word export are tabulated in the following sections:
For PDF Export

Method Parameters Return type Descriptions

GridExportToPDF FileName, ActionResults Used to export the grid


contents to Pdf format.
(IEnumarable<T>) PdfVersion,
ExportOption

For Word Export

Method Parameters Return type Descriptions

© 2014 Syncfusion. All rights reserved. 494 | Page


Essential Grid for ASP.NET MVC Classic

GridExportToWord FileName, ActionResults Used to export the grid


(IEnumarable<T>) contents to word format.
DocumentVersion,
ExportOption

4.8.6 Events
For PDF Export

Name Description Arguments


OnQueryExportPdfRowInfo Used for formatting rows while exporting PdfGridRow

OnQueryExportPdfCellInfo Used for formatting cells while exporting PdfGridCell ,


GridTableCellType

For Word Export

Name Description Arguments


OnQueryExportWordRowInfo Used for formatting rows while WTableRow
exporting

OnQueryExportWordCellInfo Used for formatting cells while WTableCell Cell ,


exporting GridTableCellType,

IWTextRange

4.8.7 How to Format Cells and Rows in a Grid that Was Exported
to PDF
You can use C# or VB code as shown below to format cells and rows in an exported grid.

4.8.7.1.1 For PDF


Certain events are used to format cells and rows in a grid that was exported to PDF. These are
specified in the following sections.
You can format cells in MVC Grid in two ways:

4.8.7.1.1.1 Through GridBuilder


The steps to enable the PDF exporting feature through GridBuilder are as follows:

© 2014 Syncfusion. All rights reserved. 495 | Page


Essential Grid for ASP.NET MVC Classic

1. Create a model in the application.


2. Create a strongly typed view.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Configure the grid toolbar and add a mapper to enable grid record exporting.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
-------------
-------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.PDFExport,"PDF
Export");
})

.Mappers(map =>
{
map.ExportPdfAction("ExportToPDF");
})
%>

View[cshtml]

@ { Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
-------------
-------------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.PDFExport,"PDF
Export");
})

.Mappers(map =>
{
map.ExportPdfAction("ExportToPDF");
})
}

5. Add the events for formatting rows and cells.

Controller

© 2014 Syncfusion. All rights reserved. 496 | Page


Essential Grid for ASP.NET MVC Classic

QueryExportPdfRowInfo

public ActionResult ExportToPDF(PagingParams args)


{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
var engine = data.GridExportToPDF<Order>() as
GridPDFExportActionResult<Order>;
engine.GridModel.QueryExportPdfRowInfo = OnQueryRowInfo;
return engine;
}

public void OnQueryRowInfo(PdfGridRow Row)


{
Row.Style.BackgroundBrush = new PdfSolidBrush(Color.Bisque);
}

QueryExportPdfCellInfo

public ActionResult ExportToPDF(PagingParams args)


{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
var engine = data.GridExportToPDF<Order>() as
GridPDFExportActionResult<Order>;
engine.GridModel.QueryExportPdfCellInfo = OnQueryCellInfo;
return engine;
}

public void OnQueryCellInfo(PdfGridCell cell, GridTableCellType


cellType)
{
if (cellType == GridTableCellType.ColumnHeaderCell)
{
cell.Style.BackgroundBrush = new PdfSolidBrush(Color.BlueViolet);
}
}

4.8.7.1.1.2 Through GridPropertiesModel

1. Create a model in the application.

© 2014 Syncfusion. All rights reserved. 497 | Page


Essential Grid for ASP.NET MVC Classic

2. Create a strongly typed view (Refer to How to>Strongly Typed View).


3. Add the following code to the view.

View[ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
%>

View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
}

4. Create a GridPropertiesModel and assign the grid properties in the model.

Controller

© 2014 Syncfusion. All rights reserved. 498 | Page


Essential Grid for ASP.NET MVC Classic

GridPropertiesModel <Order> model = new GridPropertiesModel


<Order>()
{
DataSource = new NorthwindDataContext().Orders.Take(200),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true
};

5. Configure the GridPropertiesModel as displayed below to accept the WordExport,


ActionMapper, and to render the toolbar.

Controller
ToolbarSettings toolbar = new ToolbarSettings ();
toolbar.Enable = true; // Used to enable the toolbar.
// Add the PDF toolbar item in toolbar with caption and mapper name.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.ExcelExport, Mapper = "ExportToPDF"});
model.ToolBar = toolbar;

6. Add the events for formatting rows and cells.

Controller

QueryExportPdfRowInfo

public ActionResult ExportToPDF(PagingParams args)


{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
var engine = data.GridExportToPDF<Order>() as
GridPDFExportActionResult<Order>;
engine.GridModel.QueryExportPdfRowInfo = OnQueryRowInfo;
return engine;
}

public void OnQueryRowInfo(PdfGridRow Row)


{
Row.Style.BackgroundBrush = new PdfSolidBrush(Color.Bisque);
}

QueryExportPdfCellInfo

© 2014 Syncfusion. All rights reserved. 499 | Page


Essential Grid for ASP.NET MVC Classic

public ActionResult ExportToPDF(PagingParams args)


{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
var engine = data.GridExportToPDF<Order>() as
GridPDFExportActionResult<Order>;
engine.GridModel.QueryExportPdfCellInfo = OnQueryCellInfo;
return engine;
}

public void OnQueryCellInfo(PdfGridCell cell, GridTableCellType


cellType)
{
if (cellType == GridTableCellType.ColumnHeaderCell)
{
cell.Style.BackgroundBrush = new PdfSolidBrush(Color.BlueViolet);
}
}

4.8.7.1.2 For Word


Certain events are used to format cells and rows in a grid that was exported to Word. These are
specified in the following content.
You can format cells in MVC Grid in two ways:

4.8.7.1.2.1 Through GridBuilder


The steps to enable the word exporting feature through GridBuilder are as follows:
1. Create a model in the application.
2. Create a strongly typed view.
3. In the view, use the Model property in the Datasource() to bind the data source.
4. Configure the grid toolbar and add a mapper to enable exporting grid records.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
----------
----------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.WordExport,"Word
Export");
})

© 2014 Syncfusion. All rights reserved. 500 | Page


Essential Grid for ASP.NET MVC Classic

.Mappers(map =>
{
map. ExportWordAction("ExportToWord");
})
%>

View[cshtml]

@ { Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
----------
----------
.ToolBar( toolbar =>
{
toolbar.Add(GridToolBarItems.WordExport,"Word
Export");
})

.Mappers(map =>
{
map. ExportWordAction("ExportToWord");
})
}

5. Add the events for formatting rows.

Controller

QueryExportWordCellInfo

public ActionResult ExportToWord(PagingParams args)


{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
var engine = data.GridExportToWord<Order>() as
GridWordExportActionResult<Order>;
engine.GridModel.QueryExportWordCellInfo = OnQueryCellInfo;
return engine;
}

public void OnQueryCellInfo(WTableCell cell, GridTableCellType


cellType, IWTextRange textRange)
{
if (cellType == GridTableCellType.ColumnHeaderCell)

© 2014 Syncfusion. All rights reserved. 501 | Page


Essential Grid for ASP.NET MVC Classic

{
textRange.CharacterFormat.FontSize = Office2007Blue.FontName;
}
}

QueryExportWordRowInfo

public ActionResult ExportToWord(PagingParams args)


{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
var engine = data.GridExportToWord<Order>() as
GridWordExportActionResult<Order>;
engine.GridModel.QueryExportWordRowInfo = OnQueryRowInfo;
return engine;
}
public void OnQueryRowInfo(WTableRow Row)
{
Row.RowFormat.BackColor = Color.AliceBlue;
}

4.8.7.1.2.2 Through GridPropertiesModel

73. Create a model in the application.


74. Create a strongly typed view (Refer to How to>Strongly Typed View).
75. Add the following code to the view.
76.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>

© 2014 Syncfusion. All rights reserved. 502 | Page


Essential Grid for ASP.NET MVC Classic

c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
%>

View[cshtml]
@ { Html.Syncfusion().Grid<Order>("OrdersGrid","GridModel", column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{0:dddd, MMMM d, yyyy}");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
column.Add(c => c.ShipPostalCode).HeaderText("Ship
postal Code");
column.Add(c =>
c.Freight).HeaderText("Frieght").Format("{Freight:#,#}");
});
}

77. Create a GridPropertiesModel and assign the grid properties in the model.

Controller

GridPropertiesModel <Order> model = new GridPropertiesModel


<Order>()
{
DataSource = new NorthwindDataContext().Orders.Take(200),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true
};

78. Configure the GridPropertiesModel as displayed below to accept the WordExport and
ActionMapper and to render the toolbar.

Controller

ToolbarSettings toolbar = new ToolbarSettings ();


toolbar.Enable = true; // Used to enable the toolbar.

© 2014 Syncfusion. All rights reserved. 503 | Page


Essential Grid for ASP.NET MVC Classic

// Add the PDF toolbar item to the toolbar with a caption and mapper
name.
toolbar.Items.Add(new ToolbarOptions() { ItemType=
GridToolBarItems.ExcelExport, Mapper = "ExportToWord"});
model.ToolBar = toolbar;

79. Add the events for formatting rows and cells.

Controller

QueryExportWordCellInfo

public ActionResult ExportToWord(PagingParams args)


{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
var engine = data.GridExportToWord<Order>() as
GridWordExportActionResult<Order>;
engine.GridModel.QueryExportWordCellInfo = OnQueryCellInfo;
return engine;
}

public void OnQueryCellInfo(WTableCell cell, GridTableCellType


cellType, IWTextRange textRange)
{
if (cellType == GridTableCellType.ColumnHeaderCell)
{
textRange.CharacterFormat.FontSize = Office2007Blue.FontName;
}
}

QueryExportWordRowInfo

public ActionResult ExportToWord(PagingParams args)


{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
var engine = data.GridExportToWord<Order>() as
GridWordExportActionResult<Order>;
engine.GridModel.QueryExportWordRowInfo = OnQueryRowInfo;
return engine;
}
public void OnQueryRowInfo(WTableRow Row)
{
Row.RowFormat.BackColor = Color.AliceBlue;

© 2014 Syncfusion. All rights reserved. 504 | Page


Essential Grid for ASP.NET MVC Classic

4.9 Formatting

Essential Grid allows you to format grid cells. You can achieve this formatting by three methods.
They are:
 Using column formatting
 Using custom actions
 Using conditional formatting

Properties

Property Description Type of the property Value it


accepts

ConditionalFo A collection from ICollection<GridConditionalForma IEnumerable of


rmats GridConditionalFormatDescrit tDescritor<T>> GridConditionalF
or that defines conditional ormatDescriptors
formats for Grid. .

Format Gets or sets format for the String Any string


column.

CssClass Used to CssClass for the the String Any class name
Column. in string format

Methods

Method Parameters Return type Description


s
QueryCellInfo(GridTableCell<T>) GridTableCell<T Void Used to format
> the cell

© 2014 Syncfusion. All rights reserved. 505 | Page


Essential Grid for ASP.NET MVC Classic

dynamically.
Executed for
every cell in
the grid.

RowDataBound(GridTableRow<T GridTableRow<T Void Used to format


>) > the row
dynamically.
Executed for
every row in
the grid.

Format(string) Format string IGridColumnBuilder<T Used to set


> the format to
the column.

CssClass(string) Class name as IGridColumnBuilder<T Used to set


string > the CssClass
to the column.

4.9.1 Column Formatting


Essential Grid for ASP.NET MVC uses the following methods for formatting the grid cells.
 Format()—Used to set the format for the column.
 CssClass()—Used to set the CssClass for the column.

4.9.1.1 Using Format()

Grid uses Format() method for formatting the column. This Format() method format both bound
columns and unbounds column data. In bound columns, it formats only the column values where
as unbound columns it formats the column by records.
Bound Columns

1. Create a model in the application (Refer to How to>Creating the Generic Collection
Model and How to>AutoFormattingClass).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, you can use its Model property in Datasource() to bind the data source.

80.
View [ASPX]

<%=Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)

© 2014 Syncfusion. All rights reserved. 506 | Page


Essential Grid for ASP.NET MVC Classic

.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
%>

81.
View [cshtml]

@{ Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Render();
}

4. Specify the format for columns using the Format() method.


82.
View [ASPX]

<%=Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Column( column =>
{
column.Add(c =>
c.Currency).HeaderText("Currency").Format("{0:$###,###.##}"
);
column.Add(c =>
c.Dates).HeaderText("Dates").Format("{0:MM/dd/yyyy
hh:mm:ss}");
column.Add(c =>
c.Number).HeaderText("Number").Format("{0:# inch}");
column.Add(c =>
c.Telephone).HeaderText("Telephone").Format("{0:1 - (###)
###-####}");
})
%>

83.
View [cshtml]

@{ Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")
.Datasource(Model)
.ShowCaption(false)
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Column( column =>

© 2014 Syncfusion. All rights reserved. 507 | Page


Essential Grid for ASP.NET MVC Classic

{
column.Add(c =>
c.Currency).HeaderText("Currency").Format("{0:$###,###.##}"
);
column.Add(c =>
c.Dates).HeaderText("Dates").Format("{0:MM/dd/yyyy
hh:mm:ss}");
column.Add(c =>
c.Number).HeaderText("Number").Format("{0:# inch}");
column.Add(c =>
c.Telephone).HeaderText("Telephone").Format("{0:1 - (###)
###-####}");
}).Render();
}

5. Run the sample. The grid will look like the following screenshot.

Figure 157: Grid with Formatting

Supported Data Formats for JSON Mode


The data format strings available for the Date and Number types in JavaScript are the same as
those that are available in .NET for the DateTime and Double types.

Types Supported Formats


Number Type  c or C: Currency
 p or P: Percentage
 d or D“: Decimal (# number of
digits)
 n or N“: Numeric (# number of digits
after decimal)

Note - e, f, g, r, x, and custom format strings


are not supported

© 2014 Syncfusion. All rights reserved. 508 | Page


Essential Grid for ASP.NET MVC Classic

Date Type  d: Short date pattern


 D: Long date pattern
 t: Short time pattern
 T: Long time pattern
 F: Full date/time pattern (long time)
 m or M: Month day pattern
 s: Sortable date/time pattern
 y or Y: Year month pattern

Note: - the standard format strings: f, F, g, G,


O, o, R, r, u, U are not supported. However,
custom format strings that use the “mmm”,
“yyyy”, “hh”, etc. formats are supported. You
can build your own date format string.

UnboundColumn
Refer to more information regarding the formatting of unbound columns in Data
Binding>Unbound Columns.

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
Navigate to Grid.MVC > Formatting > Column Formatting

4.9.1.2 Using CssClass()


Essential Grid uses CssClass() method for formatting the column with CSS styles.
1. Create a model in to application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column(column =>
{
column.Add(c =>
c.OrderID).HeaderText("Order ID");
column.Add(c =>

© 2014 Syncfusion. All rights reserved. 509 | Page


Essential Grid for ASP.NET MVC Classic

c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.ShipCountry).HeaderText("Ship Country");
column.Add(c =>
c.ShipCity).HeaderText("Ship City");
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column(column =>
{
column.Add(c =>
c.OrderID).HeaderText("Order ID");
column.Add(c =>
c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c =>
c.ShipCountry).HeaderText("Ship Country");
column.Add(c =>
c.ShipCity).HeaderText("Ship City");
}).Render(); }

4. Create CssClass in the view.

[CSS]

<style type="text/css">
.CustomCss
{
text-align:right;
background-color:Aqua;
}
</style>

© 2014 Syncfusion. All rights reserved. 510 | Page


Essential Grid for ASP.NET MVC Classic

5. Specify the CSS styles to columns using the CssClass() method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country").CssClass("CustomCss");
column.Add(c => c.ShipCity).HeaderText("Ship
City");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(c =>
c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.ShipCountry).HeaderText("Ship
Country").CssClass("CustomCss");
column.Add(c => c.ShipCity).HeaderText("Ship
City");

© 2014 Syncfusion. All rights reserved. 511 | Page


Essential Grid for ASP.NET MVC Classic

}).Render();
}

6. Run the sample. The grid will look like this:

Figure 158: Grid Formatting using CssClass()


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Formatting > Column Formatting

4.9.2 Custom Formatting


Essential Grid provides two types of actions for formatting cells:
 QueryCellInfo action
 RowDataBound action

4.9.2.1 QueryCellInfo Action


Grid formatting can be applied to different grid cell elements dynamically at run time. This can be
achieved by proper handling of QueryCellInfo action. It provides the Htmlattributes object for a
cell on demand.
QueryCellInfo is raised every time a request is made to access the style information for a cell.
You can do any type of formatting cells with this event.
It accepts GridTableCell<T> as its parameter, which can be used to customize the cells of the
grid control. For instance, you can apply styles for a given cellType by using the TableCellType
property on the instances of GridTableCell<T>.

© 2014 Syncfusion. All rights reserved. 512 | Page


Essential Grid for ASP.NET MVC Classic

The following table describes the GridTableCell<T> properties:

Properties

Property Description Type of Value it accepts Any other


property dependen
cies/sub-
properties
associate
d
Data Gets or sets data value of Generic T Any data NA
querycell.

Column Gets or sets the column GridColumn< Any NA


type of the querycell. T> GridColumn<T>

HtmlAttributes Gets or sets the IDictionary<s NA


Htmlattributes for tring,object>
customizing cells.

Text Gets or sets the value object Any object NA


renders in cell.

TableCellType Gets or sets the table cell Enum GridTableCellType NA


type of the querycell. .GroupCaptionCell
GridTableCellType
.GroupHeaderInde
ntCell
GridTableCellType
.SummaryFieldCell

GridTableCellType
.IndentCell
GridTableCellType
.TopLeftHeaderCel
l

GridTableCellType
.RowHeaderCell

GridTableCellType
.ColumnHeaderCel

© 2014 Syncfusion. All rights reserved. 513 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it accepts Any other


property dependen
cies/sub-
properties
associate
d
l

GridTableCellType
.RecordPlusMinus
Cell
GridTableCellType
.RecordFieldCell
GridTableCellType
.AlternateRecordFi
eldCell

GridTableCellType
.AlternateRecordR
owHeaderCell
GridTableCellType
.EmptyCell
GridTableCellType
.CaptionCell

4.9.2.1.1 Server Mode

4.9.2.1.1.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, you can use its Model property in Datasource() to bind the data source.

84.
View [ASPX]
<%=Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Column(column =>{

column.Add(c => c.ProductID).HeaderText("Product


ID");
column.Add(c => c.ProductName).HeaderText("Product

© 2014 Syncfusion. All rights reserved. 514 | Page


Essential Grid for ASP.NET MVC Classic

Name");
column.Add(c => c.SupplierID).HeaderText("Supplier
ID");
column.Add(c => c.UnitPrice).HeaderText("Unit
Price");
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock");
column.Add(c => c.UnitsOnOrder).HeaderText("Units On
Order");
column.Add(c => c.ReorderLevel).HeaderText("Reorder
Level");
})
%>

85.
86.
View [cshtml]
@{ Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.ShowRowHeader(false)
.AutoFormat(Skins.Sandune)
.Column(column =>{

column.Add(c => c.ProductID).HeaderText("Product


ID");
column.Add(c => c.ProductName).HeaderText("Product
Name");
column.Add(c => c.SupplierID).HeaderText("Supplier
ID");
column.Add(c => c.UnitPrice).HeaderText("Unit
Price");
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock");
column.Add(c => c.UnitsOnOrder).HeaderText("Units On
Order");
column.Add(c => c.ReorderLevel).HeaderText("Reorder
Level");
}).Render();
}

4. Configure the QueryCellInfo() action as shown below to perform custom formatting at


the cell level.
87.
88.

© 2014 Syncfusion. All rights reserved. 515 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]

<%=Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.QueryCellInfo(cell => Html.RenderAction("QueryAction",
"Formatting", new { args = cell }))
%>

89.
View [cshtml]

@{ Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.QueryCellInfo(cell => Html.RenderAction("QueryAction",
"Formatting", new { args = cell })).Render();
}
5. Create an action for the QueryAction () action as shown below to perform custom
formatting at the cell level.
Controller

public void QueryAction(GridTableCell<Product> args)


{
if (args.TableCellType == GridTableCellType.RecordFieldCell
|| args.TableCellType == GridTableCellType.AlternateRecordFieldCell)
{

if (args.Column.MappingName == "UnitsInStock")
{
if (args.Data.UnitsInStock <= 30)
args.HtmlAttributes["style"] =
"color:#ac0c0c;text-align:right";
}

if (args.Column.MappingName == "ReorderLevel")
{
if (args.Data.UnitsInStock < 25)
args.HtmlAttributes["style"] =
"color:#ac0c0c;text-align:right";
}

}
}

© 2014 Syncfusion. All rights reserved. 516 | Page


Essential Grid for ASP.NET MVC Classic

90.
91.
6. Set its data source and render the view.
92.
Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new
NorthwindDataContext().Products.Take(20).ToList();
return View(data);
}
7. In order to work with paging actions, create a Post method for Index actions, bind the
data source to the grid and assign the QueryAction to the QueryCellInfo property and
pass the data as a Aciton result to the view as shown in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Products.Take(20).ToList();
var engine = data.GridActions<Product>() as
GridHtmlActionResult<Product>;
engine.GridModel.QueryCellInfo = QueryAction;
return engine;
}

8. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 517 | Page


Essential Grid for ASP.NET MVC Classic

Figure 159: Dynamic Formatting Applied to the Grid using QueryCellInfo

4.9.2.1.1.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]
<%=Html.Syncfusion().Grid<Product>("Orders_Grid","GridModel",
column=> {
column.Add(c =>
c.ProductID).HeaderText("Product ID");
column.Add(c =>
c.ProductName).HeaderText("Product Name");
column.Add(c =>
c.SupplierID).HeaderText("Supplier ID");
column.Add(c =>
c.UnitPrice).HeaderText("Unit Price");
column.Add(c =>
c.UnitsInStock).HeaderText("Units In Stock");
column.Add(c =>
c.UnitsOnOrder).HeaderText("Units On Order");
column.Add(c =>
c.ReorderLevel).HeaderText("Reorder Level"); })%>

© 2014 Syncfusion. All rights reserved. 518 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]
@( Html.Syncfusion().Grid<Product>("Orders_Grid","GridModel",
column=> {
column.Add(c =>
c.ProductID).HeaderText("Product ID");
column.Add(c =>
c.ProductName).HeaderText("Product Name");
column.Add(c =>
c.SupplierID).HeaderText("Supplier ID");
column.Add(c =>
c.UnitPrice).HeaderText("Unit Price");
column.Add(c =>
c.UnitsInStock).HeaderText("Units In Stock");
column.Add(c =>
c.UnitsOnOrder).HeaderText("Units On Order");
column.Add(c => c.ReorderLevel).HeaderText("Reorder
Level"); }))

4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from the controller to the view using the ViewData class as shown
below.

93.
Controller

// Create a model and assign a data source.


GridPropertiesModel model = new GridPropertiesModel()
{
DataSource=new NorthwindDataClassesDataContext().Products,
Caption="Product" ,
AllowPaging = true,
AllowSorting = true
};
94.
5. Create an action for the QueryCellInfo() action as shown below to perform custom
formatting in cell level.
95.
Controller

[ChildActionOnly]
public void QueryAction(GridTableCell<Product> cell)
{
// TableCellType is validation. Check for Record field
cells.
if (cell.TableCellType == GridTableCellType.RecordFieldCell
|| cell.TableCellType == GridTableCellType.AlternateRecordFieldCell)
{

© 2014 Syncfusion. All rights reserved. 519 | Page


Essential Grid for ASP.NET MVC Classic

if (cell.Column.MappingName == "UnitsInStock")
{

if (cell.Data.UnitsInStock <= 30)


{
// Apply background color and font style for
the record field cell.
cell.HtmlAttributes["style"] =
"color:Blue;background-color:Chocolate;";
}
}

if (cell.Column.MappingName == "ReorderLevel")
{
if (cell.Data.UnitsInStock < 25)
{
// Apply background color and font style for
the record field cell.
cell.HtmlAttributes["style"] =
"color:#ac0c0c;background-color:Bisque;";
}
}

6. Bind the action to GridPropertiesModel and pass the model to the view using the View
Data method as given below:
96.
Controller

GridPropertiesModel<Product> model = new


GridPropertiesModel<Product>()
{
DataSource = new
NorthwindDataContext().Products.Take(20).ToList(),
Caption = "Product",
AllowPaging = true,
AllowSorting = true
};
model.QueryCellInfo = QueryAction;
ViewData["GridModel"] = model;

7. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 520 | Page


Essential Grid for ASP.NET MVC Classic

Figure 160: Dynamic Formatting Applied to Grid Using QueryCellInfo

4.9.2.1.2 JSON Mode

4.9.2.1.2.1 Through GridBuilder


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Set the QueryCellInfo method name using the QueryCellInfo method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ClientSideEvents(events => {
events.QueryCellInfo("QueryCellInfoHandler");
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ClientSideEvents(events => {
events.QueryCellInfo("QueryCellInfoHandler");
}).Render();

© 2014 Syncfusion. All rights reserved. 521 | Page


Essential Grid for ASP.NET MVC Classic

6. Render the view.

Controller
public ActionResult Index()
{
return View();
}

7. In order to work with the JSON mode actions, create a Post method for Index actions
and bind the data source to the grid as given in the following code.
97.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

8. Format the Grid cell using QueryCellInfoHandler.


JavaScript

function QueryCellInfoHandler(sender, args) {


if (args.Column.Name == "CustomerID")
$(args.Element).css('color', 'Red').css('font-weight', 'bolder');
}

9. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 522 | Page


Essential Grid for ASP.NET MVC Classic

Figure 161: CustomerID Column is Formatted

4.9.2.1.2.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}))

© 2014 Syncfusion. All rights reserved. 523 | Page


Essential Grid for ASP.NET MVC Classic

4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to set
the JSON mode.
5. Set the QueryCellInfo handler name using the QueryCellInfo property.

[Controller]
public ActionResult Index()
{
ClientSideEvents eve = new ClientSideEvents();
eve.QueryCellInfo = "QueryCellInfoHandler";

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
ActionMode = ActionMode.JSON,
ClientSideEvents = eve

};

ViewData["GridModel"] = gridModel;
return View();
}

6. Format the grid cells using QueryCellInfoHandler.

98.
JavaScript

function QueryCellInfoHandler(sender, args) {


if (args.Column.Name == "CustomerID")
$(args.Element).css('color', 'Red').css('font-weight', 'bolder');
}
99.
7. In order to work with the JSON mode, create a Post method for Index actions and bind the
data source to the grid as given in the code sample below.
100.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

8. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 524 | Page


Essential Grid for ASP.NET MVC Classic

Figure 162: CustomerID Column is Formatted

4.9.2.1.2.3 Tables for properties, methods, and events


Properties

Property Description Type Data type


ActionMode Gets or sets the Server side ActionMode
ActionMode for the
Grid.
Possible Values:

ActionMode.JSON
ActionMode.Server

Default value:

ActionMode.Server

Methods

Method Description Parameters Type Return type

© 2014 Syncfusion. All rights reserved. 525 | Page


Essential Grid for ASP.NET MVC Classic

ActionMode Gets the (ActionMode mode) Server-side Void


ActionMode for
Possible Values:
the Grid.
ActionMode.JSON

ActionMode.Server

Default value:
ActionMode.Server

4.9.2.2 RowDataBound Action

Grid formatting can be applied to different grid row elements dynamically at run time. This can be
achieved by RowDataBound action. It provides the Htmlattributes object for a cell on demand.
RowDataBound is raised every time a request is made to access the style information for a row.
You can do any type of row formatting with this event.
It accepts GridTableRow<T> as its parameter which can be used to customize the rows of the
Grid control.
The following table describes the GridTableRow<T> properties:
Properties

Property Description Type of the property Value it Any other


accepts dependencies/sub-
properties
associated
Data Gets or sets Generic T Any data NA
Data for the
current row.

HtmlAttributes Gets or sets IDictionary<string,object> Any NA


the dictionary
Htmlattributes value
for
customizing
cells.

IsAlternate Indicates Boolean True/False NA


whether the
record row is

© 2014 Syncfusion. All rights reserved. 526 | Page


Essential Grid for ASP.NET MVC Classic

alternate.

4.9.2.2.1 Server Mode

4.9.2.2.1.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, use the Model property in Datasource() to bind the data source.

View [ASPX]

<%=Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.Column(column =>{

column.Add(c => c.ProductID).HeaderText("Product ID");


column.Add(c => c.ProductName).HeaderText("Product
Name");
column.Add(c => c.SupplierID).HeaderText("Supplier
ID");
column.Add(c => c.UnitPrice).HeaderText("Unit Price");
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock");
column.Add(c => c.UnitsOnOrder).HeaderText("Units On
Order");
column.Add(c => c.ReorderLevel).HeaderText("Reorder
Level");
})
%>

101.
View [cshtml]

@{ Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()

.Column(column =>{

column.Add(c => c.ProductID).HeaderText("Product ID");


column.Add(c => c.ProductName).HeaderText("Product
Name");

© 2014 Syncfusion. All rights reserved. 527 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(c => c.SupplierID).HeaderText("Supplier


ID");
column.Add(c => c.UnitPrice).HeaderText("Unit Price");
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock");
column.Add(c => c.UnitsOnOrder).HeaderText("Units On
Order");
column.Add(c => c.ReorderLevel).HeaderText("Reorder
Level");
}).Render();
}

4. Configure the RowDataBound() action as given below to perform custom formatting at the
row level.
102.
View [ASPX]

<%=Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.RowDataBound(row => Html.RenderAction("RowAction",
"Formatting", new { args = row }))
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Product>("CustomGrid")
.Datasource(Model)
.Caption("Products")
.EnablePaging()
.RowDataBound(row => Html.RenderAction("RowAction",
"Formatting", new { args = row })).Render();
}

5. Create an action for the RowDataBound() as shown below to perform custom formatting at
the cell level.
Controller

public void RowAction(GridTableRow<Product> row)


{
if (row.Data.UnitPrice < 20)
row.HtmlAttributes["style"] = "background:
#FFD6A4;color:#13771a;font-family:Verdana;font-weight:bold;";
}

103.
104.
6. Set its data source and render the view.

© 2014 Syncfusion. All rights reserved. 528 | Page


Essential Grid for ASP.NET MVC Classic

105.
Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new
NorthwindDataContext().Products.Take(20).ToList();
return View(data);
}
7. In order to work with paging actions, create a Post method for Index actions, bind the data
source to the grid and assign the QueryAction to the QueryCellInfo property and pass the
data as a Aciton result to the view as shown in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Products.Take(20).ToList();
var engine = data.GridActions<Product>() as
GridHtmlActionResult<Product>;
engine.GridModel.RowDataBound = RowAction;
return engine;
}
106.
8. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 529 | Page


Essential Grid for ASP.NET MVC Classic

Figure 163: Dynamic Formatting Applied to the Grid Using RowDataBound()

4.9.2.2.1.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

107.
View [ASPX]

<%=Html.Syncfusion().Grid<Product>("Product_Grid","GridModel", column=>
{
column.Add(c =>
c.ProductID).HeaderText("Product ID");
column.Add(c =>
c.ProductName).HeaderText("Product Name");
column.Add(c =>
c.SupplierID).HeaderText("Supplier ID");
column.Add(c =>
c.UnitPrice).HeaderText("Unit Price");
column.Add(c =>
c.UnitsInStock).HeaderText("Units In Stock");
column.Add(c =>
c.UnitsOnOrder).HeaderText("Units On Order");
column.Add(c =>
c.ReorderLevel).HeaderText("Reorder Level");
})%>

© 2014 Syncfusion. All rights reserved. 530 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]
@( Html.Syncfusion().Grid<Product>("Product_Grid","GridModel",
column=> { column.Add(c =>
c.ProductID).HeaderText("Product ID");
column.Add(c =>
c.ProductName).HeaderText("Product Name");
column.Add(c =>
c.SupplierID).HeaderText("Supplier ID");
column.Add(c =>
c.UnitPrice).HeaderText("Unit Price");
column.Add(c =>
c.UnitsInStock).HeaderText("Units In Stock");
column.Add(c =>
c.UnitsOnOrder).HeaderText("Units On Order");
column.Add(c =>
c.ReorderLevel).HeaderText("Reorder Level");
}))

4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from the controller to the view using the ViewData class as shown
below.

Controller

//Create a model and assign the data source.


GridPropertiesModel model = new GridPropertiesModel()
{
DataSource=new
NorthwindDataClassesDataContext().Products,
Caption="Product" ,
AutoFormat=Skins.Sandune

};

5. Create an action for the RowDataBound() action as given below to perform custom
formatting at the row level.
108.
Controller

[ChildActionOnly]
public void RowAction(GridTableRow<Product> row)
{
//Apply style to row whose UnitPrices are less than 20.
if (row.Data.UnitPrice < 20)
row.HtmlAttributes["style"] = "background-
color:#C3C3F2;color:#13771a;font-family:Verdana;font-weight:bold;";

© 2014 Syncfusion. All rights reserved. 531 | Page


Essential Grid for ASP.NET MVC Classic

6. Bind the action to GridPropertiesModel and pass the model to the view using the
ViewData method as given below:
109.
Controller

GridPropertiesModel<Product> model = new


GridPropertiesModel<Product>()
{
DataSource = new
NorthwindDataContext().Products.Take(20).ToList(),
Caption = "Product",
AutoFormat = Skins.Sandune
};
model.RowDataBound = RowAction;
ViewData["GridModel"] = model;

7. Run the application. The grid will appear as shown below.

Figure 164: Dynamic Formatting Applied to a Grid using RowDataBound()

4.9.2.2.2 JSON Mode

4.9.2.2.2.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. Set the RowDataBound handler name using the RowDataBound method.

© 2014 Syncfusion. All rights reserved. 532 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ClientSideEvents(events => {
events.RowDataBound("RowDataBoundHandler");
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.ClientSideEvents(events => {
events.RowDataBound("RowDataBoundHandler");
}).Render();

6. Render the view.


Controller
public ActionResult Index()
{
return View();
}

7. In order to work with JSON mode actions, create a Post method for Index actions
and bind the data source to the grid as given in the following code sample.
110.
Controller
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

© 2014 Syncfusion. All rights reserved. 533 | Page


Essential Grid for ASP.NET MVC Classic

8. Format the Grid cell using QueryCellInfoHandler.

JavaScript

function RowDataBoundHandler (sender, args) {


if (args.Data != null) {
if (args.Data.OrderID == “10584”)
$(args.Element).css('color', 'green').css('font-weight',
'bolder');
}
}

9. Run the application. The grid will appear as shown below.

Figure 165: Grid with OrderID 10584 Row Formatted

4.9.2.2.2.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

© 2014 Syncfusion. All rights reserved. 534 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
)

4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to


set the JSON mode.
5. Set the RowDataBound handler name using the QueryCellInfo property.

[Controller]
public ActionResult Index()
{
ClientSideEvents eve = new ClientSideEvents();
eve.RowDataBound = "RowDataBoundHandler";

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
ActionMode = ActionMode.JSON,
ClientSideEvents = eve

};

ViewData["GridModel"] = gridModel;
return View();
}

6. Format the grid cell using QueryCellInfoHandler.


111.

© 2014 Syncfusion. All rights reserved. 535 | Page


Essential Grid for ASP.NET MVC Classic

JavaScript

function RowDataBoundHandler(sender, args) {


if (args.Data != null) {
if (args.Data.OrderID == “10584”)
$(args.Element).css('color', 'green').css('font-weight',
'bolder');
}
}

112.
7. In order to work with JSON mode, create a Post method for Index actions and bind the
data source to the grid as given in the following code.
113.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
return data.GridJSONActions<Order>();
}

8. Run the application. The Grid will appear as shown below.

Figure 166: Grid with OrderID 10584 Row Formatted

© 2014 Syncfusion. All rights reserved. 536 | Page


Essential Grid for ASP.NET MVC Classic

4.9.2.2.2.3 Tables for properties, methods, and events


Properties

Property Description Type Data type


ActionMode Gets or sets the Server side ActionMode
ActionMode for the
Grid.
Possible Values:
ActionMode.JSON
ActionMode.Server

Default value:
ActionMode.Server

Methods

Method Description Parameters Type Return type

ActionMode Gets the (ActionMode mode) Server-side Void


ActionMode for
Possible Values:
the Grid.
ActionMode.JSON
ActionMode.Server

Default value:
ActionMode.Server
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
Navigate to Grid.MVC > Formatting > Custom Formatting

4.9.3 Conditional Formating


Essential Grid has built-in support for conditional formatting. This feature allows you to format the
grid cells based on a certain condition. This can be achieved by defining a
GridConditionalFormatDescriptor<T> for the grid.

© 2014 Syncfusion. All rights reserved. 537 | Page


Essential Grid for ASP.NET MVC Classic

There are two ways to adding conditional format to the grid .


1. Through GridBuilder
2. Through GridPropertiesModel.

4.9.3.1 Through GridBuilder


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, you can use its Model property in Datasource() to bind the data source.
114.
View [ASPX]
<%= GridDataCondition<Product> condition1 = new
GridDataCondition<Product>(c => c.UnitPrice) { ConditionType =
GridDataConditionType.GreaterThan, Value = 30 };
GridDataCondition<Product> condition2 = new
GridDataCondition<Product>(c => c.UnitsInStock) { ConditionType =
GridDataConditionType.GreaterThan, Value = 50 };
GridConditionalFormatDescriptor<Product> cFormat = new
GridConditionalFormatDescriptor<Product>();
cFormat.Name = "c1";
cFormat.ApplyStyleToColumn = "ProductName";
cFormat.Conditions.Add(condition1);
cFormat.Conditions.Add(condition2);
cFormat.Cell.HtmlAttributes["style"] = "background-color:
#1BA1E2 ;Color:#FFFFFF;";

GridDataCondition<Product> condition3 = new


GridDataCondition<Product>(c => c.CategoryID) { ConditionType =
GridDataConditionType.Equals, Value = 2 };
GridConditionalFormatDescriptor<Product> rowFormat = new
GridConditionalFormatDescriptor<Product>();
rowFormat.Name = "condition1";
rowFormat.Conditions.Add(condition3);
rowFormat.Cell.HtmlAttributes["style"] =
"background:#F9AE17;color:white;";

System.Collections.ObjectModel.Collection<GridConditionalFormatDescript
or<Product>> cf = new
System.Collections.ObjectModel.Collection<GridConditionalFormatDescript
or<Product>>();
cf.Add(cFormat);
cf.Add(rowFormat);
%>

<%= Html.Syncfusion().Grid<Product>("ConditionalGrid")
.Datasource(Model)
.Caption("Products")

© 2014 Syncfusion. All rights reserved. 538 | Page


Essential Grid for ASP.NET MVC Classic

.Column(column =>
{
column.Add(c => c.ProductID).HeaderText("Product
ID").Width(100);
column.Add(c => c.ProductName).HeaderText("Product
Name");
column.Add(c => c.CategoryID).HeaderText("Category
ID").Width(100);
column.Add(c => c.UnitPrice).HeaderText("Unit
Price").Format("{0:C2}").Width(100);
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock").Width(100);
})
.EnablePaging()
.EnableSorting()%>

115.
116.
View [cshtml]
@{ GridDataCondition<Product> condition1 = new
GridDataCondition<Product>(c => c.UnitPrice) { ConditionType =
GridDataConditionType.GreaterThan, Value = 30 };
GridDataCondition<Product> condition2 = new
GridDataCondition<Product>(c => c.UnitsInStock) { ConditionType =
GridDataConditionType.GreaterThan, Value = 50 };
GridConditionalFormatDescriptor<Product> cFormat = new
GridConditionalFormatDescriptor<Product>();
cFormat.Name = "c1";
cFormat.ApplyStyleToColumn = "ProductName";
cFormat.Conditions.Add(condition1);
cFormat.Conditions.Add(condition2);
cFormat.Cell.HtmlAttributes["style"] = "background-color:
#1BA1E2 ;Color:#FFFFFF;";

GridDataCondition<Product> condition3 = new


GridDataCondition<Product>(c => c.CategoryID) { ConditionType =
GridDataConditionType.Equals, Value = 2 };
GridConditionalFormatDescriptor<Product> rowFormat = new
GridConditionalFormatDescriptor<Product>();
rowFormat.Name = "condition1";
rowFormat.Conditions.Add(condition3);
rowFormat.Cell.HtmlAttributes["style"] =
"background:#F9AE17;color:white;";

System.Collections.ObjectModel.Collection<GridConditionalFormatDescript
or<Product>> cf = new
System.Collections.ObjectModel.Collection<GridConditionalFormatDescript
or<Product>>();

© 2014 Syncfusion. All rights reserved. 539 | Page


Essential Grid for ASP.NET MVC Classic

cf.Add(cFormat);
cf.Add(rowFormat);
}

@{ Html.Syncfusion().Grid<Product>("ConditionalGrid")
.Datasource(Model)
.Caption("Products")
.Column(column =>
{
column.Add(c => c.ProductID).HeaderText("Product
ID").Width(100);
column.Add(c => c.ProductName).HeaderText("Product
Name");
column.Add(c => c.CategoryID).HeaderText("Category
ID").Width(100);
column.Add(c => c.UnitPrice).HeaderText("Unit
Price").Format("{0:C2}").Width(100);
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock").Width(100);
})
.ConditionalFormats(c => { c.Add(cf); })
.EnablePaging()
.EnableSorting()
.Render();
}

4. Create an action for the CondtionalFormats() action as shown below to perform


condtional formatting for grid contents.
117.
Controller

private Collection<GridConditionalFormatDescriptor<Product>>
ConditionFormats
{
get
{
GridDataCondition<Product> condition1 = new
GridDataCondition<Product>(c => c.UnitPrice) { ConditionType =
GridDataConditionType.GreaterThan, Value = 30 };
GridDataCondition<Product> condition2 = new
GridDataCondition<Product>(c => c.UnitsInStock) { ConditionType =
GridDataConditionType.GreaterThan, Value = 50 };
GridConditionalFormatDescriptor<Product> cFormat = new
GridConditionalFormatDescriptor<Product>();
cFormat.Name = "c1";
cFormat.ApplyStyleToColumn = "ProductName";
cFormat.Conditions.Add(condition1);
cFormat.Conditions.Add(condition2);
cFormat.Cell.HtmlAttributes["style"] = "background-
color: #1BA1E2 ;Color:#FFFFFF;";

GridDataCondition<Product> condition3 = new

© 2014 Syncfusion. All rights reserved. 540 | Page


Essential Grid for ASP.NET MVC Classic

GridDataCondition<Product>(c => c.CategoryID) { ConditionType =


GridDataConditionType.Equals, Value = 2 };
GridConditionalFormatDescriptor<Product> rowFormat =
new GridConditionalFormatDescriptor<Product>();
rowFormat.Name = "condition1";
rowFormat.Conditions.Add(condition3);
rowFormat.Cell.HtmlAttributes["style"] =
"background:#F9AE17;color:white;";

Collection<GridConditionalFormatDescriptor<Product>> cf
= new Collection<GridConditionalFormatDescriptor<Product>>();
cf.Add(cFormat);
cf.Add(rowFormat);
return cf;
}
}

5. Create a GridPropertiesModel in the Index method. Use the ConditionalFormats


property to assign the conditional formatting collection. Pass the model to the view
using the ViewData. The ViewData name is same as that of the Grid control Id which is
mentioned in the Index page.
118.
119.
Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Products.ToList();
return View(data);
}

6. In order to work with conditional formatting actions after grid post action, create a Post
method for Index actions , bind the data source to the grid and pass the data to the
view as a ActionResult as given in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.

© 2014 Syncfusion. All rights reserved. 541 | Page


Essential Grid for ASP.NET MVC Classic

/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Products.ToList();
ActionResult result = data.GridActions<Product>();
var engineSource = result as GridHtmlActionResult<Product>;
engineSource.GridModel.ConditionalFormats =
this.ConditionFormats;
return engineSource; }

7. Run the application. The grid will appear as shown below.

Figure 167: Applying Condtional Formatting for grid contents

4.9.3.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
120.
View [ASPX]

<%= Html.Syncfusion().Grid<Product>("ConditionalGrid", column =>{


column.Add(c => c.ProductID).HeaderText("Product
ID").Width(100);
column.Add(c => c.ProductName).HeaderText("Product
Name");
column.Add(c => c.CategoryID).HeaderText("Category
ID").Width(100);
column.Add(c => c.UnitPrice).HeaderText("Unit

© 2014 Syncfusion. All rights reserved. 542 | Page


Essential Grid for ASP.NET MVC Classic

Price").Format("{0:C2}").Width(100);
column.Add(c => c.UnitsInStock).HeaderText("Units
In Stock").Width(100);
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Product>("ConditionalGrid", column =>{
column.Add(c => c.ProductID).HeaderText("Product
ID").Width(100);
column.Add(c => c.ProductName).HeaderText("Product Name");
column.Add(c => c.CategoryID).HeaderText("Category
ID").Width(100);
column.Add(c => c.UnitPrice).HeaderText("Unit
Price").Format("{0:C2}").Width(100);
column.Add(c => c.UnitsInStock).HeaderText("Units In
Stock").Width(100);
}))

4. Create an action for the CondtionalFormats() action as shown below to perform condtional
formatting for grid contents.
121.
Controller

private Collection<GridConditionalFormatDescriptor<Product>>
ConditionFormats
{
get
{
GridDataCondition<Product> condition1 = new
GridDataCondition<Product>(c => c.UnitPrice) { ConditionType =
GridDataConditionType.GreaterThan, Value = 30 };
GridDataCondition<Product> condition2 = new
GridDataCondition<Product>(c => c.UnitsInStock) { ConditionType =
GridDataConditionType.GreaterThan, Value = 50 };
GridConditionalFormatDescriptor<Product> cFormat = new
GridConditionalFormatDescriptor<Product>();
cFormat.Name = "c1";
cFormat.ApplyStyleToColumn = "ProductName";
cFormat.Conditions.Add(condition1);
cFormat.Conditions.Add(condition2);
cFormat.Cell.HtmlAttributes["style"] = "background-
color: #1BA1E2 ;Color:#FFFFFF;";

GridDataCondition<Product> condition3 = new


GridDataCondition<Product>(c => c.CategoryID) { ConditionType =
GridDataConditionType.Equals, Value = 2 };
GridConditionalFormatDescriptor<Product> rowFormat =
new GridConditionalFormatDescriptor<Product>();
rowFormat.Name = "condition1";

© 2014 Syncfusion. All rights reserved. 543 | Page


Essential Grid for ASP.NET MVC Classic

rowFormat.Conditions.Add(condition3);
rowFormat.Cell.HtmlAttributes["style"] =
"background:#F9AE17;color:white;";

Collection<GridConditionalFormatDescriptor<Product>> cf
= new Collection<GridConditionalFormatDescriptor<Product>>();
cf.Add(cFormat);
cf.Add(rowFormat);
return cf;
}
}

5. Create a GridPropertiesModel in the Index method. Use the ConditionalFormats


property to assign the conditional formatting collection. Pass the model to the view using
the ViewData. The ViewData name is same as that of the Grid control Id which is
mentioned in the Index page.
122.
Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Product> model = new
GridPropertiesModel<Product>();
model.DataSource = new
NorthwindDataContext().Products.ToList();
model.Caption = "Product";
model.AllowPaging = true;
model.AllowSorting = true;
model.ConditionalFormats = this.ConditionFormats;
ViewData["ConditionalGrid"] = model;
return View();
}

6. In order to work with conditional formatting actions after grid post action, create a Post
method for Index actions , bind the data source to the grid and pass the data to the view as
a ActionResult as given in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. Required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>

© 2014 Syncfusion. All rights reserved. 544 | Page


Essential Grid for ASP.NET MVC Classic

/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Products.ToList();
ActionResult result = data.GridActions<Product>();
var engineSource = result as GridHtmlActionResult<Product>;
engineSource.GridModel.ConditionalFormats =
this.ConditionFormats;
return engineSource;
}

7. Run the application. The grid will appear as shown below.

Figure 168: Applying Condtional Formatting for grid contents


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Formatting > Conditional Formatting

4.10 Summaries

The Grid control allows you to display summaries. Summaries let you derive additional
information from your data like averages, maximums, summations, counts, and more.
For instance, you can get the number of records or maximum value and so on. They display the
calculation results in separate display rows. The summary values are calculated using Linq
expressions.

© 2014 Syncfusion. All rights reserved. 545 | Page


Essential Grid for ASP.NET MVC Classic

The Grid control provides the following built-in summary types.


 Int32Aggregate, DoubleAggregate (Average, Minimum, Maximum, Sum)
 BooleanAggregate (Count, FalseCount, TrueCount)
 Count

Summary Rows

The GridPropertiesModel.SummaryRows manages the collection of summary rows for the grid.
It is the GridSummaryRowDescriptorCollection that manages the summaries for the given
data source containing one entry for each summary. Each GridSummaryRowDescriptor in this
collection has a name that identifies the SummaryRowDescriptors for which summaries are
calculated for and a SummaryType property that defines the type of calculations to be
performed. Possible options for SummaryType are: Count, BooleanAggregate,
Int32Aggregate, DoubleAggregate.

Properties

Property Description Type of Value it Any other


property accepts dependen
cies/sub-
properties
associated
AllowSummari Used to enable or disable bool True/False NA
es the summary feature.

Default value is False.

SummaryRow A collection from GridSummaryRo Dependent


s GridSummaryRwoDecriptor wDescriptorColl with
that declares summary rows ection AllowSumma
each with a multiple ries.
GridSummaryColumnDescri
ptor elements.

Name Name used to identify in the


Summary collection.

SummaryType Specify the build-in Enum SummaryType


summary type for .Int32Aggregate,
SummaryColumnDescriptor.
SummaryType
.DoubleAggrega
te,
SummaryType
.BooleanAggreg
ate,

© 2014 Syncfusion. All rights reserved. 546 | Page


Essential Grid for ASP.NET MVC Classic

SummaryType
.Count

DataMember Specifies summary column string


used to perform the
summary calculation.

Format Indicates the format for the string


text applied on the column.

Prefix Specifies the text displayed string


before the summary column
value.

Suffix Indicates the text displayed string


after the summary column
value.

DisplayColumn Gets or sets the target string


column at which to display
the summary.

Title Specifies the text displayed string


on the summary row.

SummaryColu Used to add summary GridSummaryCo


mns columns in the Summary lumnDescriptorC
row. ollection

Methods

Method Parameters Class Retur Description


n
type
Add(GridSummaryColu GridSummaryCol GridSummaryColu Int Adds
mnDescriptor value) umnDescriptor mnDescriptorCollec GridSummaryCol
tion umnDescriptor to
the end of the
collection.

AddRange(GridSummar Array of GridSummaryColu Void Adds multiple


yColumnDescriptor[] GridSummaryCol mnDescriptorCollec GridSummaryCol
summaryColumnDescri umnDescriptors tion umnDescriptor at
the end of the

© 2014 Syncfusion. All rights reserved. 547 | Page


Essential Grid for ASP.NET MVC Classic

ptors) collection.

Clear() No parameter GridSummaryColu Void Removes all


mnDescriptorCollec GridSummaryCol
tion umnDescriptor
from the
collection.

Contains(GridSummary GridSummaryCol GridSummaryColu bool Determines if the


ColumnDescriptor umnDescriptor mnDescriptorCollec GridSummaryCol
value) tion umnDescriptor
belongs to this
Collection.

Contains(string name) Name of the bool Determines if the


SummaryColumn GridSummaryCol
GridSummaryColu
Descriptor umnDescriptor
mnDescriptorCollec
with the specified
tion
name belongs to
this Collection.

IndexOf(GridSummaryC GridSummaryCol GridSummaryColu int Returns the


olumnDescriptor value) umnDescriptor mnDescriptorCollec zero-based index
tion of the
occurrence of
the
GridSummaryCol
umnDescriptor in
the collection

IndexOf(string name) Name of the GridSummaryColu int Returns the


SummaryColumn mnDescriptorCollec zero-based index
Descriptor tion of the
occurrence of
the
GridSummaryCol
umnDescriptor
that matches the
name in the
collection.

Insert(int index, Index, GridSummaryColu void Inserts a


GridSummaryColumnD GridSummaryCol mnDescriptorCollec descriptor
escriptor value) umnDescriptor tion element into the
collection at the

© 2014 Syncfusion. All rights reserved. 548 | Page


Essential Grid for ASP.NET MVC Classic

specified index.

Remove(GridSummary GridSummaryCol GridSummaryColu void Removes the


ColumnDescriptor umnDescriptor mnDescriptorCollec specified
value) tion GridSummaryCol
umnDescriptor
from the
collection.

RemoveAt(int index) Index GridSummaryColu void Removes the


mnDescriptorCollec GridSummaryCol
tion umnDescriptor
that matches the
specified name
from the
collection.

Add(GridSummaryRow GridSummaryRo GridSummaryRow int Adds


Descriptor value) wDescriptor DescriptorCollectio GridSummaryRo
n wDescriptor to
the end of the
collection.

Clear() No Parameter GridSummaryRow void Removes all


DescriptorCollectio GridSummaryRo
n wDescriptor from
the collection.

Contains(GridSummary GridSummaryRo GridSummaryRow bool Determines if the


RowDescriptor value) wDescriptor DescriptorCollectio GridSummaryRo
n wDescriptor
belongs to this
Collection.

Contains(string name) Name of the GridSummaryRow bool Determines if the


SummaryRowDe DescriptorCollectio GridSummaryRo
scriptor n wDescriptor with
the specified
name belongs to
this Collection.

IndexOf(GridSummaryR GridSummaryRo GridSummaryRow int Returns the


owDescriptor value) wDescriptor DescriptorCollectio zero-based index
n of the
occurrence of
the

© 2014 Syncfusion. All rights reserved. 549 | Page


Essential Grid for ASP.NET MVC Classic

GridSummaryRo
wDescriptor in
the collection.

IndexOf(string name) Name of the GridSummaryRow int Returns the


SummaryRowDe DescriptorCollectio zero-based index
scriptor n of the
occurrence of
the
GridSummaryRo
wDescriptor that
matches the
name in the
collection.

Insert(int index, Index, GridSummaryRow void Inserts a


GridSummaryRowDescr GridSummaryRo DescriptorCollectio descriptor
iptor value) wDescriptor n GridSummaryRo
wDescriptor into
the collection at
the specified
index.

Remove(GridSummary GridSummaryRo GridSummaryRow void Removes the


RowDescriptor value) wDescriptor DescriptorCollectio specified
n GridSummaryRo
wDescriptor from
the collection.

Remove(string name) Name of the GridSummaryRow void Removes the


GridSummaryRo DescriptorCollectio specified
wDescriptor n GridSummaryRo
wDescriptor from
the collection
that matches the
name.

RemoveAt(int index) Index GridSummaryRow void Removes the


DescriptorCollectio GridSummaryRo
n wDescriptor that
matches the
specified name
from the
collection.

© 2014 Syncfusion. All rights reserved. 550 | Page


Essential Grid for ASP.NET MVC Classic

4.10.1 Server Mode


4.10.1.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.

View [ASPX]

<%=Html.Syncfusion().Grid<Student>("StudentGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( column => {
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p => p.Title).HeaderText("Course
Title");
column.Add(P => P.Duration);
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course
Fees");
column.Add(p => p.CGPA);
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Student>("StudentGrid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.AllowSummaries(true)
.AutoFormat(Skins.Sandune)
.Column( column => {
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p => p.Title).HeaderText("Course
Title");
column.Add(P => P.Duration);
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course

© 2014 Syncfusion. All rights reserved. 551 | Page


Essential Grid for ASP.NET MVC Classic

Fees");
column.Add(p => p.CGPA);
}).Render();
}

4. Create a GridPropertiesModel in the Index method..

Controller

// Create an instance to GridPropertiesModel.


GridPropertiesModel<Student> gridModel = new
GridPropertiesModel<Student>();

5. Set up a summary column by instantiating GridSummaryColumnDescriptor


specifying the SummaryType and format.

Controller

// Create instance to GridSummaryColumnDescriptor.


GridSummaryColumnDescriptor maxCGPA = new
GridSummaryColumnDescriptor();
maxCGPA.Name = "Maximum CGPA";// Specify the name of
the summary column.
maxCGPA.SummaryType = SummaryType.DoubleAggregate;//
Specify the summary type.
maxCGPA.DataMember = "CGPA";// Gets or sets the
mapping for this column.
maxCGPA.DisplayColumn= "CGPA";// The target column
at which to display the summary.
maxCGPA.Format = "{Maximum:##.##}";// The format string
used to format the text to display in the summary column.

6. Define a SummaryRow and add the SummaryColumn to it.

Controller

/// A GridSummaryRowDescriptor declares a summary row


with one or multiple GridSummaryColumnDescriptor
elements.
/// <param name="name">The descriptor name.</param>
GridSummaryRowDescriptor maxRow = new
GridSummaryRowDescriptor("Largest");

/// Title displayed in the summary row.

© 2014 Syncfusion. All rights reserved. 552 | Page


Essential Grid for ASP.NET MVC Classic

maxRow.Title = "Largest";

/// Custom text which can be prefixed with the


maxCGPA summary.
maxCGPA.Prefix = "Max:";

/// Summary columns are added into the summary row.


maxRow.SummaryColumns.Add(maxCGPA);

7. Finally add the summary row to the grid using SummaryRows.

Controller

// Add summary rows to the grid.


foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
gridModel.SummaryRows.Add(summaryRow);

Note: In this sample, SummaryRows are defined inside the private property “SummaryRows”

8. Pass the GridPropertiesModel to the view using the ViewData() method. Use the
grid’s ID as the key in ViewData.

Controller
// Pass the GridPropertiesModel to the grid using GridID. Here
StudentGrid is the grid's ID.
ViewData["StudentGrid"] = gridModel;

9. If you enable the paging and sorting features, rebind the SummaryRow property again
in Post actions as given below.

Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)

© 2014 Syncfusion. All rights reserved. 553 | Page


Essential Grid for ASP.NET MVC Classic

{
IEnumerable data = new
StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList();

ActionResult result = data.GridActions<Student>();


var engineSource = result as GridHtmlActionResult<Student>;

// Rebinding the summary rows.


foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
engineSource.GridModel.SummaryRows.Add(summaryRow);

return result;
}

10. Run the sample. The grid will appear as shown below.

Figure 169: Grid with Summary Rows

4.10.1.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
123.
View [ASPX]

<%=Html.Syncfusion().Grid<Student>("StudentGrid",
"GridModel", column =>
{
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p =>

© 2014 Syncfusion. All rights reserved. 554 | Page


Essential Grid for ASP.NET MVC Classic

p.Title).HeaderText("Course Title");
column.Add(P => P.Duration);
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course
Fees");
column.Add(p => p.CGPA);
}) %>

View [cshtml]

@( Html.Syncfusion().Grid<Student>("StudentGrid", "GridModel", column


=>
{
column.Add(p =>
p.UniversityCode).HeaderText("University Code");
column.Add(p =>
p.Title).HeaderText("Course Title");
column.Add(P => P.Duration);
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course
Fees");
column.Add(p => p.CGPA);
})
)

4. Create a GridPropertiesModel in the Index action method. Use the AllowSummaries


property to enable the summaries feature.

Controller

GridPropertiesModel<Student> gridModel = new


GridPropertiesModel<Student>()
{
DataSource = new
StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList(),
Caption="Student Details",
AllowPaging=true,
AllowSorting=true,
AllowSummaries=true,
AutoFormat=Skins.Sandune
};

© 2014 Syncfusion. All rights reserved. 555 | Page


Essential Grid for ASP.NET MVC Classic

5. Set up a summary column by instantiating GridSummaryColumnDescriptor


specifying the SummaryType and format.

Controller

// Create instance to GridSummaryColumnDescriptor.


GridSummaryColumnDescriptor maxCGPA = new
GridSummaryColumnDescriptor();
maxCGPA.Name = "Maximum CGPA";// Specify the name to
summary column.
maxCGPA.SummaryType = SummaryType.DoubleAggregate;//
Specify the SummaryType.
maxCGPA.DataMember = "CGPA";// Gets or sets the
mapping for this column.
maxCGPA.DisplayColumn= "CGPA";// The target column
to which the summary is displayed.
maxCGPA.Format = "{Maximum:##.##}";// The format string
used to format the text to display in the summary column.

6. Define a SummaryRow and add the SummaryColumn into it.


124.
Controller

/// A GridSummaryRowDescriptor declares a summary row


with one or multiple GridSummaryColumnDescriptor
elements.
/// <param name="name">The descriptor name.</param>
GridSummaryRowDescriptor maxRow = new
GridSummaryRowDescriptor("Largest");

/// Title displayed in the summary row.


maxRow.Title = "Largest";

/// Custom text which can be prefixed with the


maxCGPA summary.
maxCGPA.Prefix = "Max:";

/// Summary columns are added into the summary row.


maxRow.SummaryColumns.Add(maxCGPA);

125. Finally add the summary row to the grid using SummaryRows.

Controller

// Add summary rows to the grid.


foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
gridModel.SummaryRows.Add(summaryRow);

© 2014 Syncfusion. All rights reserved. 556 | Page


Essential Grid for ASP.NET MVC Classic

ViewData["GridModel"] = gridModel;

Note: In this sample, summary rows are defined inside the private property “SummaryRows”.

126. If you enable the paging and sorting features, rebind the SummaryRow property again in
Post actions as given below.

Controller
/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties. </param>
/// <returns>
/// HtmlActionResult returns the data displayed in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList();

ActionResult result = data.GridActions<Student>();


var engineSource = result as GridHtmlActionResult<Student>;

// Rebinding the SummaryRows.


foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
engineSource.GridModel.SummaryRows.Add(summaryRow);

return result;
}

127. Run the sample. The grid will look like this:
Figure 170: Grid with Summary Rows
Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Summary > Summaries

© 2014 Syncfusion. All rights reserved. 557 | Page


Essential Grid for ASP.NET MVC Classic

4.10.2 JSON Mode

JSON (JavaScript Object Notation) is a lightweight data-interchange format for serializing


structured data. It defines a small set of formatting rules for the portable representation of
structured data. It is human readable, platform independent, and has a wide availability of
implementations. We can use this JSON format to exchange data in the MVC architecture.

Use Case Scenarios


 High performance: The grid will be quickly rendered because in initialize rendering of table
will not work so easy rendering of grid is performed and will be easily rendered to the
browser.
 Encapsulation: Objects are encapsulated to another object for security purposes.
 Reduction of postback time: In the server side we are not rendering the grid content, so
postback time will be reduced.

4.10.2.1 Through GridBuilder

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON action mode using the ActionMode method.
5. To enable summaries, use the AllowSummaries method.
128.

© 2014 Syncfusion. All rights reserved. 558 | Page


Essential Grid for ASP.NET MVC Classic

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Summaries(summary => {
summary.AllowSummaries(true)

.Add((IEnumerable<GridSummaryRowDescriptor>)ViewData["SummaryRowDescrip
tors"]);
})
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.ActionMode(ActionMode.JSON)
.Summaries(summary => {
summary.AllowSummaries(true)

.Add((IEnumerable<GridSummaryRowDescriptor>)ViewData["SummaryRowDescrip
tors"]);
})
.Column( columns => {
columns.Add(p => p.OrderID);
columns.Add(p => p.CustomerID);
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}).Render();
}

6. Set up a summary column by instantiating GridSummaryColumnDescriptor


specifying the summary type and format.
129.
Controller
// Create an instance to GridSummaryColumnDescriptor.
GridSummaryColumnDescriptor maxCGPA = new
GridSummaryColumnDescriptor();

© 2014 Syncfusion. All rights reserved. 559 | Page


Essential Grid for ASP.NET MVC Classic

maxCGPA.Name = "Maximum CGPA"; // Specify the name


to summary column.
maxCGPA.SummaryType = SummaryType.DoubleAggregate;//
Specify the SummaryType.
maxCGPA.DataMember = "CGPA"; // Gets or sets the
mapping for this column.
maxCGPA.DisplayColumn= "CGPA"; // The target column
to which to display the summary.
maxCGPA.Format = "{Maximum:##.##}";// The format string
used to format the text to display in the summary column.

7. Define a SummaryRow and add the SummaryColumn to it.

Controller
GridSummaryRowDescriptor maxRow = new
GridSummaryRowDescriptor("Largest");
/// Title displayed in the summary Row.
maxRow.Title = "Largest";
/// Custom text which can be prefixed with the
maxCGPA summary.
maxCGPA.Prefix = "Max:";
/// Summary columns are added into the Summary
row.
maxRow.SummaryColumns.Add(maxCGPA);

8. Finally, set the list of SummaryRowDescriptor to ViewData.

Controller
ViewData[“SummaryRowDescriptors”] =
this.SummaryCollection;

9. Render the view.


130.
Controller
public ActionResult Index()
{
return View();
}

10. If you enable the paging and sorting features, rebind the SummaryRow property again
in Post action as given below.
131.
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new

© 2014 Syncfusion. All rights reserved. 560 | Page


Essential Grid for ASP.NET MVC Classic

StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList();
ActionResult result = data.GridJSONActions<Student>();
var engineSource = result as GridJSONActionResult<Student>;
// Rebinding the SummaryRows.
foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
engineSource.GridModel.SummaryRows.Add(summaryRow);
return result;
}

11. Run the application. The grid will appear as shown below.

Figure 171: Summary-Enabled Grid

4.10.2.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
})%>

© 2014 Syncfusion. All rights reserved. 561 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID)
columns.Add(p => p.CustomerID)
columns.Add(p => p.EmployeeID);
columns.Add(P => P.ShipCountry);
columns.Add(p => p.OrderDate).Format("{0:dd-MM-yyyy}");
}))

4. Create a GridPropertiesModel in the Index method. Use the ActionMode property to


set the JSON mode.
5. Use the AllowSummaries property to enable the summaries.

[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Sandune,
AllowSummaries = true,
ActionMode = ActionMode.JSON

};

ViewData["GridModel"] = gridModel;
return View();
}

6. Set up a summary column by instantiating the GridSummaryColumnDescriptor


specifying the SummaryType and format.
132.
Controller

// Create instance to GridSummaryColumnDescriptor.


GridSummaryColumnDescriptor maxCGPA = new
GridSummaryColumnDescriptor();
maxCGPA.Name = "Maximum CGPA"; // Specify the name
of the summary column.
maxCGPA.SummaryType = SummaryType.DoubleAggregate;//
Specify the summary type.
maxCGPA.DataMember = "CGPA";// Gets or sets the
mapping for this column.
maxCGPA.DisplayColumn= "CGPA";// The target column
in which to display the summary.
maxCGPA.Format = "{Maximum:##.##}";// The format string
used to format the text to display in the summary column.

© 2014 Syncfusion. All rights reserved. 562 | Page


Essential Grid for ASP.NET MVC Classic

7. Define a SummaryRow and add the SummaryColumn to it.


133.
Controller

/// A GridSummaryRowDescriptor declares a summary row


with one or multiple GridSummaryColumnDescriptor
elements.
/// <param name="name">The descriptor name.</param>
GridSummaryRowDescriptor maxRow = new
GridSummaryRowDescriptor("Largest");

/// Title displayed in the summary row.


maxRow.Title = "Largest";

/// Custom text which can be prefixed with the


maxCGPA summary.
maxCGPA.Prefix = "Max:";

/// Summary columns are added to the summary row.


maxRow.SummaryColumns.Add(maxCGPA);

134. Finally, add the summary row to the grid using SummaryRows.
Controller

// Add summary rows to the grid.


foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
gridModel.SummaryRows.Add(summaryRow);

ViewData["GridModel"] = gridModel;

8. If you enable the paging and sorting features, rebind the SummaryRow property again
in Post actions as given below.
135.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().AutoFormatStudent.Skip(0).Take(20).ToList();
ActionResult result = data.GridActions<Student>();
var engineSource = result as GridHtmlActionResult<Student>;
// Rebinding the SummaryRows.
foreach (GridSummaryRowDescriptor summaryRow in
this.SummaryCollection)
engineSource.GridModel.SummaryRows.Add(summaryRow);
return result;
}

© 2014 Syncfusion. All rights reserved. 563 | Page


Essential Grid for ASP.NET MVC Classic

9. Run the application. The grid will appear as shown below:

Figure 172: Summary-Enabled Grid

4.11 Scrolling
Essential Grid’s scrolling feature allows you to scroll through the grid manually.
Another feature that we have implemented under scrolling is virtual scrolling.

4.11.1 Scrolling
Essential Grid now allows you to specify the required width and height for a grid. You can scroll
through the grid manually. Also, the width property in the ColumnBuilder can be used to set the
width for individual grid columns in both design time and run time.
Properties

Property Description Type of Value it Any other


property accepts dependencies/sub-
properties
associated
AllowScrolling Enables/disables Boolean True/False NA
the scroll bars in
a grid.

Width Gets or sets the Integer NA


width of grid.

Height Gets or sets the Integer NA

© 2014 Syncfusion. All rights reserved. 564 | Page


Essential Grid for ASP.NET MVC Classic

height of grid.

IGridColumnBuilder.Width Gets or sets the Integer NA


width of
individual
column in view
page.

Methods

Method Parameters Return type Description


AllowScrolling(bool) bool IScrollingBuilder Used to enable/disable the
scroll bars in a grid.

Width(int) integer IScrollingBuilder Used to set the grid width.

Height(int) integer IScrollingBuilder Used to set the gridcontent


height.

width(int) integet IGridColumnBuilder<T> Used to set the column


width.

Essential Grid’s scrolling feature allows you to scroll through the grid manually.
Another feature that we have implemented under scrolling is that of virtual scrolling.

4.11.1.1 Through GridBuilder


1. Create a model in to application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.
136.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>

© 2014 Syncfusion. All rights reserved. 565 | Page


Essential Grid for ASP.NET MVC Classic

p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
%>

137.
View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}).Render();
}

4. Specify the column width using the Width() method in IGridColumnBuilder<T>.


138.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID").Width(200);
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order

© 2014 Syncfusion. All rights reserved. 566 | Page


Essential Grid for ASP.NET MVC Classic

Date").Format("{0:dd-MM-yyyy}");
})
%>

139.
View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID").Width(200);
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}).Render();
}

5. Enable the scrolling feature by the AllowScrolling() method. Specify the grid width and
height by using Width() and Height().
140.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.Scrolling( scroll => {
scroll.AllowScrolling(true);
scroll.Height(400);
scroll.Width(900);
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(200);
columns.Add(p => p.EmployeeID).HeaderText("Employee

© 2014 Syncfusion. All rights reserved. 567 | Page


Essential Grid for ASP.NET MVC Classic

ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.PageSettings(page => page.PageSize(20))
.EnableSorting()
.Scrolling( scroll => {
scroll.AllowScrolling(true);
scroll.Height(400);
scroll.Width(900);
})
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(200);
columns.Add(p => p.EmployeeID).HeaderText("Employee
ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}).Render();
}

6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 568 | Page


Essential Grid for ASP.NET MVC Classic

Figure 173: Grid with Scroll Bar

4.11.1.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrderGrid","GridModel", columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("OrderGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID");
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID");
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}))

4. Specify the column width using the Width() method in IGridColumnBuilder<T>.

© 2014 Syncfusion. All rights reserved. 569 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrderGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID").Width(200);
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("OrderGrid","GridModel",
columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p =>
p.CustomerID).HeaderText("Customer ID").Width(200);
columns.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship
Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}))

5. Create a GridPropertiesModel in the Index method. Use the AllowScrolling property to


enable the scrolling feature.

Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{

© 2014 Syncfusion. All rights reserved. 570 | Page


Essential Grid for ASP.NET MVC Classic

DataSource = new NorthwindDataContext().Orders,


Caption="Orders",
AllowPaging=true,
PageSize=20,
AllowSorting=true,
AllowScrolling=true,
AutoFormat=Skins.Sandune
};

6. Specify the grid width and height by using the Width and Height properties.

Controller

GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Order>()


{
DataSource = new NorthwindDataContext().Orders,
Caption="Orders",
AllowPaging=true,
PageSize=20,
AllowSorting=true,
AllowScrolling=true,
Width=900,
Height=400,
AutoFormat=Skins.Sandune
};

7. Run the application. The grid will appear as shown below.

Figure 174: Grid with Scroll Bar


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Rows and Columns > Scrolling Grid

© 2014 Syncfusion. All rights reserved. 571 | Page


Essential Grid for ASP.NET MVC Classic

4.11.2 Virtual Scrolling in MVC Grid


The virtual scrolling support in Essential Grid for MVC allows you to view data that you require
without buffering the entire load of a huge database.
This is done by dynamically loading records from server while already loaded rows remain on the
client side.

Use Case Scenario


Virtual scrolling allows you to retrieve the data you want through smart rendering. This means you
don’t have to wait until whole databases are loaded for you to get the data you want.

ScrollSettings Properties Table


Descripti Type of
Property Value it accepts Dependencies
on property
AllowVirtualScro Gets or bool True AllowScrolling—
lling sets
False Scrolling should
whether
be enabled
VirtualScroll
ing is
enabled or
not.

VirtualScrollMod Gets or VirtualScroll VirtualScrollMode.No AllowVirtualScrolli


e sets the Mode rmal ng—
mode of
VirtualScrollMode.Fa Virtual Scrolling
scrolling
cebook should be
enabled

Default value is
VirtualScrollMode.No
rmal

Scrolling Methods

Method Description Arguments


AllowVirtualScrolling Gets or sets whether bool
VirtualScrolling is
enabled or not.

VirtualScrollMode Gets or sets the mode VirtualScrollMode


of scrolling

© 2014 Syncfusion. All rights reserved. 572 | Page


Essential Grid for ASP.NET MVC Classic

4.11.2.1 Virtual Scrolling Mode


There are two virtual scrolling modes are available:
 Normal Mode
 FaceBook Mode

4.11.2.1.1 Normal Mode


You can enable virtual scrolling through two ways, namely:
 Through GridBuilder
 Through GridPropertiesModel

4.11.2.1.1.1 Through GridBuilder


1. Create a model in the application.
2. Create a strongly typed view.
3. Call the AllowVirtualScrolling method to enable or disable virtual scrolling in the grid.
View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.Scrolling(scroll=>{
scroll.AllowVirtualScrolling(true); // Enabling
virtual scrolling.

})

----

%>

View[cshtml]

@{

© 2014 Syncfusion. All rights reserved. 573 | Page


Essential Grid for ASP.NET MVC Classic

Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.Scrolling(scroll=>{
scroll.AllowVirtualScrolling(true); // Enabling
virtual scrolling.

})

----
.Render()

4. Set the data source and render the view.


141.
Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
}

5. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code:
142.
Controller

<summary>

© 2014 Syncfusion. All rights reserved. 574 | Page


Essential Grid for ASP.NET MVC Classic

/// Paging/editing/filtering requests are mapped to this


method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

6. Run the application. You can see the grid loaded with the initial items and upon scrolling the
required data is loaded.

Figure 175: Grid with Initial Items Loaded

Figure 176: Grid on Scrolling

© 2014 Syncfusion. All rights reserved. 575 | Page


Essential Grid for ASP.NET MVC Classic

Figure 177: Required Data Loaded on Scrolling Completed

4.11.2.1.1.2 Through GridProperties Model


143. Create a model in the application.
144. Create a strongly typed view (Refer to How to>Strongly Typed View).
145. Add the following code in the Index.aspx file to create the Grid control in the view.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
})%>

View[cshtml]

@{Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
}).Render();

© 2014 Syncfusion. All rights reserved. 576 | Page


Essential Grid for ASP.NET MVC Classic

)}

146. Create a GridPropertiesModel in the Index action.


147. To enable the context menu, set the EnableContextMenu to True as shown in the
following code samples:

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",

-----
};
gridModel.Scrolling.AllowVirtualScrolling = true; //
Enabling virtual scrolling.

ViewData["GridModel"] = gridModel;
return View();
}

/// <summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

148. Run the application. You can see the grid with the initial records loaded and upon
scrolling, the required data is loaded.

© 2014 Syncfusion. All rights reserved. 577 | Page


Essential Grid for ASP.NET MVC Classic

Figure 178: Grid with Initial Items Loaded

Figure 179: Grid on Scrolling

Figure 180: Required Data Loaded on Scrolling Completed


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).

© 2014 Syncfusion. All rights reserved. 578 | Page


Essential Grid for ASP.NET MVC Classic

2. Navigate to Grid.MVC > Product Showcase > Virtual Scrolling

4.11.2.1.2 Facebook Mode


You can configure virtual scrolling in the following two ways:
a. Through GridBuilder
b. Through GridPropertiesModel

4.11.2.1.2.1 Through GridBuilder


1. Create a model in the application.
2. Create a strongly typed view.
3. Call the AllowVirtualScrolling method to enable/disable virtual scrolling in the grid.
4. Call the VirtualScroll method to set the virtual scrolling mode to the normal or Facebook
modes.
View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.Scrolling(scroll=>{
scroll.AllowVirtualScrolling(true)

.VirtualScrollMode(VirtualScrollMode.Facebook); // Configuring virtual


scroll modes.
})
----

%>

© 2014 Syncfusion. All rights reserved. 579 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.Scrolling(scroll=>{
scroll.AllowVirtualScrolling(true)

.VirtualScrollMode(VirtualScrollMode.Facebook); // Configuring virtual


scroll modes.
})

----
.Render()

5. Set the data source and render the view.


Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
}

6. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code.
Controller

© 2014 Syncfusion. All rights reserved. 580 | Page


Essential Grid for ASP.NET MVC Classic

<summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

7. Run the application. You can see the grid with the initial records loaded and on scrolling the
required data is loaded.

Figure 181: Initial Items Loaded in the Facebook Mode

4.11.2.1.2.2 Through GridPropertiesModel


1. Create a model in the application.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
})%>

© 2014 Syncfusion. All rights reserved. 581 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]

@{Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
}).Render();
)}

4. Create a GridPropertiesModel in the Index action.


5. To enable/disable virtual scrolling, set the AllowVirtualScrolling property as shown in the
code samples below:

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
-----
};
gridModel.Scrolling.AllowVirtualScrolling = true;

gridModel.Scrolling.VirtualScrollMode =
VirtualScrollMode.Facebook; // Configuring virtual scroll modes.

ViewData["GridModel"] = gridModel;
return View();
}

/// <summary>
/// Paging/editing/filtering requests are mapped to this

© 2014 Syncfusion. All rights reserved. 582 | Page


Essential Grid for ASP.NET MVC Classic

method. This method invokes the HtmlActionResult


/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

6. Run the application. You can see the grid with the initial records loaded and during
scrolling, the required data is loaded.

Figure 182: Initial Items Loaded in the Facebook Mode


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Product Showcase > Virtual Scrolling

4.12 Selection

You can select one or more rows/records of the Grid using some keyboard keys. Before
selecting, you need to enable this feature by setting the Selection property to True.
Properties

Property Description Type of Value it accepts Any other


propert dependencies/su

© 2014 Syncfusion. All rights reserved. 583 | Page


Essential Grid for ASP.NET MVC Classic

y b-properties
associated

AllowSelection Enables/disable bool True/false NA


s the selection
feature in grid.

AllowColumnSelecti Enables/Disabl bool True/false NA


on es the column
selection I grid.

RowsSelectionMode Gets or Sets Enum RowsSelectionMo NA


the row de .Toggle,
selection mode
RowsSelectionMo
for grid.
de .Normal

Methods

Method Parameters Return type Description


AllowSelection(bool) bool IGridBuilder<T Used to
> Enable/disable
the selection
mode.

AllowColumnSelection(bool) bool IGridBuilder<T Used to


> enable/disable the
column selection.

RowSelectionMode(RowSelectionMo RowSelectionMod IGridBuilder<T Used to set the


de) e enum value > RowSelectionMod
e in grid.

After enabling the AllowSelection property, select any one row at run time. Now, by holding
CTRL, you will be able to select other rows also using the left mouse button as in the image
below.

The following are possible.


 Columns can be selected by clicking the upper 1/4 of their headers.
 Rows can be selected either by clicking the row header or any cell of the row.
 The whole grid can be selected by clicking the cell at the upper-left corner of the grid.
 The ESC key is used to clear the selection.

© 2014 Syncfusion. All rights reserved. 584 | Page


Essential Grid for ASP.NET MVC Classic

 For multiple selections, use SHIFT+arrow keys for continuous selection of consecutive
rows.
 Press CTRL and left-click to select random rows for multiple selections.
Selection is enabled by default.

Various selection styles


1. Column selection.

Figure 183: Column Selection

2. CTRL+mouse-click selection.
149.

Figure 184: CTRL+Mouse Selection


3. Grid selection.
150.

© 2014 Syncfusion. All rights reserved. 585 | Page


Essential Grid for ASP.NET MVC Classic

Figure 185: Grid Selection

4. Row selection.

Figure 186: Row Selection


5. SHIFT+arrow keys selection.
151.

© 2014 Syncfusion. All rights reserved. 586 | Page


Essential Grid for ASP.NET MVC Classic

Figure 187: Shift+Arrow Keys Selection

4.12.1 Toggle Selection


The Toggle selection mode allows you to perform an selection and unselection of the particular
row. When the Toggle selection is enabled, if you click on the selected row then it will be
unselected and viceversa.

4.12.1.1 Through GridBuilder

To enable the ToggleSelection feature you need to perform the following.


152. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.

© 2014 Syncfusion. All rights reserved. 587 | Page


Essential Grid for ASP.NET MVC Classic

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")

.Datasource((IEnumerable<Order>)ViewData["ToggleGrid"])
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");

})
.EnablePaging()
.AutoFormat(Skins.Sandune)
.RowsSelectionMode(RowsSelectionMode.Toggle)
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")

.Datasource((IEnumerable<Order>)ViewData["ToggleGrid"])
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");

})
.EnablePaging()
.AutoFormat(Skins.Sandune)
.RowsSelectionMode(RowsSelectionMode.Toggle)
.Render();
}

© 2014 Syncfusion. All rights reserved. 588 | Page


Essential Grid for ASP.NET MVC Classic

4. Set the data source in the action and render the view.

[Controller]

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{

ViewData["ToggleGrid"] = new
NorthwindDataContext().Orders.ToList();
return View();
}

5. Run the application and select any row in the grid. The grid will appear as shown below.

Figure 188: Grid with Row Selected

If you click on the selected row, the selected row will be unselected as shown in the following
screenshot.

© 2014 Syncfusion. All rights reserved. 589 | Page


Essential Grid for ASP.NET MVC Classic

Figure 189: Grid with Row Unselected

4.12.1.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the HomeController.cs file to create the Grid control in the view.

[Controller]

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the Grid.</returns>
public ActionResult OrderGrid()
{

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.ToList(),
AutoFormat = Skins.Sandune,
Caption = "First Grid Order",
AllowPaging = true,
RowsSelectionMode = RowsSelectionMode.Toggle
};

ViewData["GridModel"] = gridModel;

return View();

© 2014 Syncfusion. All rights reserved. 590 | Page


Essential Grid for ASP.NET MVC Classic

4. Create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");

})
%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.OrderDate).HeaderText("Order Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p =>
p.Freight).HeaderText("Freight");

}))

5. Run the application and select any row in the grid. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 591 | Page


Essential Grid for ASP.NET MVC Classic

Figure 190: Grid with Row Selected

If you click on the selected row, the selected row will be unselected as shown in the following
screenshot.

Figure 191: Grid with Row Unselected


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
Navigate to Grid.MVC > User Interaction > Toggle Selection Mode

4.13 Drag and Drop


4.13.1 Dragging and Dropping Grid Rows into Any Other
Element

© 2014 Syncfusion. All rights reserved. 592 | Page


Essential Grid for ASP.NET MVC Classic

This feature allows you to select multiple rows (using jQuery UI Selectable) and drag and drop
the selected rows to any other element which is specified using the TargetHtmlElementId
property of the grid.

Properties

Property Description Type of Value it Any other


property accepts dependencies/su
b-properties
associated
TargetHtmlElementID Gets or sets the selector String Any string value AllowRowsDragging
identification of the
TargetElement to Drop.

ie, To represent ID:


“#TargetID”,
To represent class:
“.TargetClassname”

RowsDraggingMode This property sets the type of Enum DragandDropMod AllowRowsDragging


dragand drop mode. Options e.GhostRows
are Normal and GhostRows.
DragandDropMod
e.Normal

AllowRowsDragging This property enables this Boolean Any Boolean NA


Rows Drag and Drop feature value
and JQuery UI Selection.

RowsDroppingMappe This property sets the string Any string value AllowRowsDragging
r mapping string. To update the
source grid while dropping the
rows, if you need one Action
means you can give here.

For Example: if you move


rows from one grid to another
grid in Source grid the rows
needs to be removed from
database.

© 2014 Syncfusion. All rights reserved. 593 | Page


Essential Grid for ASP.NET MVC Classic

Methods

Method Parameters Return Descriptions


type
TargetHtmlElementID String IGridBuilder Used to set the
selector
identification of the
TargetElement to
Drop.
ie, To represent ID:
“#TargetID”,
To represent
class:
“.TargetClassname”

RowsDraggingMode DragandDropMode.GhostRows IGridBuilder Used to set which


type of dragand
DragandDropMode.Normal
drop mode. Options
are Normal and
GhostRows.

AllowRowsDragging Boolean IGridBuilder Used to enable this


Rows Drag and
Drop feature and
JQuery UI
Selection.

RowsDroppingMapper String IGridBuilder Used to set the


mapping string, to
update the source
grid while dropping
the rows, if you
need one Action
means you can give
here.

For Example: if you


move rows from
one grid to another
grid in Source grid

© 2014 Syncfusion. All rights reserved. 594 | Page


Essential Grid for ASP.NET MVC Classic

the rows needs to


be removed from
database.

Events

Name Description Arguments


OnRowDropping The event which call its handler after draging operation and Event,
before dropping operation. Here you are providing option to
Data
cancel the drop. gridObject contains DroppingCancel variable
if it is set as True. Dropping will be cancelled.

OnRowDropped The event which calls the handler after dropped operation. By Event,
this event you can update your own target element by using
Data
ajax post.

4.13.1.1 Through GridBuilder

To enable the row drag-and-drop feature you need to perform the following.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in Datasource() to bind the data source.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("GridSrc")

.Datasource((IEnumerable<Order>)ViewData["data"])
.Caption("First Grid Order")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");

})
.AllowRowsDragging(true)
.AllowDragAndDrop(false)
.TargetHtmlElementId("#GridDest")
.RowsDraggingMode(DragandDropMode.GhostRows)

© 2014 Syncfusion. All rights reserved. 595 | Page


Essential Grid for ASP.NET MVC Classic

.AutoFormat(Skins.Midnight)
.RowsDroppingMapper("Dragged")
.ClientSideEvents(events => {
events.OnRowDropping("OnDropping");
events.OnRowDropped("DroppedTarget");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("GridSrc")

.Datasource((IEnumerable<Order>)ViewData["data"])
.Caption("First Grid Order")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");

})
.AllowRowsDragging(true)
.AllowDragAndDrop(false)
.TargetHtmlElementId("#GridDest")
.RowsDraggingMode(DragandDropMode.GhostRows)
.AutoFormat(Skins.Midnight)
.RowsDroppingMapper("Dragged")
.ClientSideEvents(events => {
events.OnRowDropping("OnDropping");
events.OnRowDropped("DroppedTarget");
}).Render();
}

2. Set the data source in the Index action and render the view.
153.
[Controller]

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
ViewData["data"] = GridOrders.SrcOrders;
ViewData["dataDest"] = GridOrders.DestOrders;

© 2014 Syncfusion. All rights reserved. 596 | Page


Essential Grid for ASP.NET MVC Classic

if (ControllerContext.HttpContext.Request.IsAjaxRequest())
{
return PartialView("DragResetPartialView",
this.ViewData);
}
return View();

Now you can select any rows in your grid and drop them into any other target element. In the
sample, you set the target element as another grid. Please refer to example above. The following
screenshot shows rows being dropped in another element.

Figure 192: Drag and Drop of Grid Records

4.13.1.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the HomeController.cs file to create the Grid control in the view.

[Controller]

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult OrderGrid()

© 2014 Syncfusion. All rights reserved. 597 | Page


Essential Grid for ASP.NET MVC Classic

{
GridPropertiesModel<Order> Srcmodel= new
GridPropertiesModel<Order>()
{
DataSource = GridOrders.SrcOrders,
Caption = "First Grid Order",
AllowRowsDragging = true,
AllowDragAndDrop = false,
TargetHtmlElementId = "#GridDest",
RowsDraggingMode = DragandDropMode.GhostRows,
AutoFormat = Skins.Midnight,
RowsDroppingMapper = "Dragged",
OnRowDropping = "OnDropping",
OnRowDropped="DroppedTarget"
};
ViewData["SrcGrid"] = Srcmodel;
Return View();
}

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("GridSrc","SrcGrid",column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");

})
%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("GridSrc","SrcGrid",column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");

}))

© 2014 Syncfusion. All rights reserved. 598 | Page


Essential Grid for ASP.NET MVC Classic

Now you can select any rows in your grid and drop them into any other target element. In the
sample, you set the target element as another grid. Please refer to example above. The following
screenshot shows rows being dropped in another element.

Figure 193: Drag and Drop of Grid Records

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Drag-and-Drop > Grid-to-Grid

4.13.2 Drag Any Other Element and Drop into Grid


This feature allows you to drag any element using jQuery UI Draggable and drop it into your
grid. You can also drop any element into a specified row in the table.

Properties

Property Type Value it Dependency Description


accepts
Droppable Boolean Any Normal This property sets
boolean your Grid as
value Droppable.

© 2014 Syncfusion. All rights reserved. 599 | Page


Essential Grid for ASP.NET MVC Classic

ElementtoDrag String Any string Dependecy on This property sets


value Droppable the Target
element to be
dragged. String
must be like a
normal selector.
ie, To represent
ID: “#TargetID”,
To represent
class:
“.TargetClassnam
e”

EnableSelectionOnDraggi Boolean Any Dependecy on This property is


ng boolean Droppable property set if a row needs
value to be selected
while draggable
element is
dragging on your
GridRow. This
happens only if no
row is already
selected.

EnableHighlighting Boolean Any Dependecy on This property is


boolean Droppable and set if a row(the
value EnableSelectionOnDr current row which
agging property is accepting the
Droppable) needs
to be Highlighted
while draggable
element is
dragging on your
GridRow.

Methods
Method Parameter Return Description
type type
Droppable Boolean IGridBuilder This property sets your Grid as
Droppable.

© 2014 Syncfusion. All rights reserved. 600 | Page


Essential Grid for ASP.NET MVC Classic

ElementtoDrag String IGridBuilder This property sets the Target


element to be dragged. String
must be like a normal selector.
ie, To represent ID:
“#TargetID”,

To represent class:
“.TargetClassname”

EnableSelectionOnDragging Boolean IGridBuilder This property is set if a row


needs to be selected while
draggable element is dragging
on your GridRow. This happens
only if no row is already
selected.

EnableHighlighting Boolean IGridBuilder This property is set if a row(the


current row which is accepting
the Droppable) needs to be
Highlighted while draggable
element is dragging on your
GridRow.

Events

Name Description Arguments


OnGridRowDragEvent The event which call its handler while dragging in any Event,
of the grid row. In this event you are passing the Grid
Data,
object, Json Record of the selected row and the
dragging element. DragElement

OnGridRowsDropEvent The event which calls the handler after dropped Event,
operation. By this event you can update your own
Data,
target element by using ajax post. In this event you are
passing the Grid object, Json Record of the selected DragElement
row and the element that is dropped.

© 2014 Syncfusion. All rights reserved. 601 | Page


Essential Grid for ASP.NET MVC Classic

4.13.2.1 Through GridBuilder

To enable the drag any other element and drop it into grid rows feature you need to perform the
following:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view you can use its Model property in DataSource to bind the data source.

View [ASPX]

<%=Html.Syncfusion().Grid<ShoppingCart>("Grid1")

.Datasource((IEnumerable<ShoppingCart>)ViewData["CartGrid"])
.Caption("Shopping Cart")
.Column(column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.Count).HeaderText("Count");
column.Add(p =>
p.Price).HeaderText("Price").Format("${Price:0.00}");

})
.Droppable(true)
.ElementtoDrag(".ItemsDraggable")
.AutoFormat(Skins.Marble)
.EnableHighlighting(true)
.EnableSelectionOnDragging(true)
.ClientSideEvents(events=>{

events.OnGridRowsDropEvent("DroppedTarget");
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<ShoppingCart>("Grid1")

.Datasource((IEnumerable<ShoppingCart>)ViewData["CartGrid"])
.Caption("Shopping Cart")
.Column(column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.Count).HeaderText("Count");

© 2014 Syncfusion. All rights reserved. 602 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p =>
p.Price).HeaderText("Price").Format("${Price:0.00}");

})
.Droppable(true)
.ElementtoDrag(".ItemsDraggable")
.AutoFormat(Skins.Marble)
.EnableHighlighting(true)
.EnableSelectionOnDragging(true)
.ClientSideEvents(events=>{

events.OnGridRowsDropEvent("DroppedTarget");
}).Render();

[Controller]

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{

ViewData["CartGrid"] =
ShoppingCartOrders.CartOrders.Where(p => p.Count > 0).ToList();
return View();
}

4.13.2.2 Through GridPropertiesModel


1. Create a model in to application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the HomeController.cs file to create the Grid control in the
view.

[Controlller]

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult OrderGrid()
{
GridPropertiesModel<ShoppingCart> gridModel = new
GridPropertiesModel<ShoppingCart>()
{

© 2014 Syncfusion. All rights reserved. 603 | Page


Essential Grid for ASP.NET MVC Classic

DataSource = ShoppingCartOrders.CartOrders.Where(p =>


p.Count > 0).ToList(),
AutoFormat = Skins.Marble,
AllowDragAndDrop = false,
Caption = "Shopping Cart",
Droppable = true,
EnableHighlighting = false,
EnableSelectionOnDragging = false,
OnGridRowsDropEvent = "DroppedTarget",
ElementtoDrag = ".ItemsDraggable"
};

ViewData["GridModel"] = gridModel;
return View();

View [ASPX]

<%=Html.Syncfusion().Grid<ShoppingCart>(
"Grid1", "GridModel",column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.Count).HeaderText("Count");
column.Add(p =>
p.Price).HeaderText("Price").Format("${Price:0.00}");

})

View [cshtml]
@( Html.Syncfusion().Grid<ShoppingCart>(
"Grid1", "GridModel",column =>
{
column.Add(p =>
p.ProductID).HeaderText("Product ID");
column.Add(p =>
p.Count).HeaderText("Count");
column.Add(p =>
p.Price).HeaderText("Price").Format("${Price:0.00}");

})

© 2014 Syncfusion. All rights reserved. 604 | Page


Essential Grid for ASP.NET MVC Classic

The following screenshot shows that any element within the ElementtoDrag Selector can be
dragged. Here the items are set as draggable elements.

Figure 194: Element Dragged to Drag Selector

The following screenshot shows the dropped grid that is updated using the event.

Figure 195: Grid Updated Using the Event


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Drag-and-Drop > Shopping Cart

© 2014 Syncfusion. All rights reserved. 605 | Page


Essential Grid for ASP.NET MVC Classic

4.13.2.3 Properties Explanation

EnableSelectionOnDragging: Type: Boolean (Dependency on Droppable property)


This property is set if a row needs to be selected while a draggable element is being dragged on
your GridRow. This happens only if no row is already selected.
The following screenshot explains the EnableSelectionOnDragging.
When EnableSelectionOnDragging is True:

GridPropertiesModel model = new GridPropertiesModel();


model. EnableSelectionOnDragging =true;

Figure 196: EnableSelectionOnDragging is True

When EnableSelectionOnDragging is False:

GridPropertiesModel model = new GridPropertiesModel();


model. EnableSelectionOnDragging =false;

Figure 197: EnableSelectionOnDragging is False

© 2014 Syncfusion. All rights reserved. 606 | Page


Essential Grid for ASP.NET MVC Classic

EnableHighlighting: Type: Boolean (Dependency on EnableSelectionOnDragging property)


This property is set if a row (the current row accepting the droppable item) needs to be
highlighted while draggable element is dragging on your GridRow.
Following screenshot explains the EnableHighlighting.
When EnableHighlighting is True:

GridPropertiesModel model = new GridPropertiesModel();


model.EnableHighlighting =true;

Case 1: If Now row is already selected.


In this screenshot, you can understand that the current Dragging row is selected and also
denotes that highlighted row is ready to accept the drop.

Figure 198: Dragging Row is Selected

Case 2: If any row is already selected


In this case, on mouse move the grid always highlights the selected row. It denotes that, in this
case, the selected row is always ready to accept the drop.

Figure 199: Selected Row is Highlighted

When EnableHighlighting is False:

© 2014 Syncfusion. All rights reserved. 607 | Page


Essential Grid for ASP.NET MVC Classic

GridPropertiesModel model = new GridPropertiesModel();


model.EnableHighlighting =false;

In this case selected row is not highlighting.

Figure 200: Selected Row is Not Highlighted

4.14 Keyboard Interface


Essential Grid for MVC provides extensive support for keyboard handling. The following
table gives the default keys for performing various key actions.
Action Default Keys
Focus Key CTRL+ALT+F

First Cell Selection HOME

Last Cell Selection END

First Row Selection CTRL+HOME

Last Row Selection CTRL+END

Insert Record INSERT

Delete Record DELETE

Edit Record F2

Save Request ENTER

Cancel Request ESC

Export to Excel ALT+X

Next Page PAGE DOWN

Previous Page PAGE UP

Next Pager ALT+PAGE DOWN

© 2014 Syncfusion. All rights reserved. 608 | Page


Essential Grid for ASP.NET MVC Classic

Previous Pager ALT+PAGE UP

Last Page CTRL+ALT+PAGE DOWN

First Page CTRL+ALT+PAGE UP

Selected Group Expand ALT+DOWN AROW

Total Group Expand CTRL+ALT+DOWN ARROW

Selected Group Collapse ALT+UP ARROW

Total Group Collapse CTRL+ALT+UP ARROW

Key Configuration: All keyboard shortcuts can be configured using the KeyConfigurator
property in the GridPropertiesModel.

Note: Keyboard shortcuts work only when the grid is in focus. Focus can be set by clicking on
any part of the grid or by using the shortcut of the Focus Key action.
In the Mozilla Firefox browser, focus can be identified by the dotted lines around the Grid object.

Figure 201: Focussed Grid in Mozillla Firefox

Use Case Scenarios


Keyboard navigation is useful when the user does not want to be dependent on mouse clicks
when interacting with the control.

© 2014 Syncfusion. All rights reserved. 609 | Page


Essential Grid for ASP.NET MVC Classic

4.14.1 Adding Keyboard Interface Support to an Application


Adding keyboard interface functionality to a grid can be done in two methods:
 Default Keys
 Configured Keys

4.14.1.1 Enabling Keyboard Interface with Default Keys


The keyboard interface feature can be enabled in two ways:
 Through GridBuilder
 Through GridPropertiesModel

4.14.1.1.1 Through GridBuilder


To enable the keyboard interface using GridBuilder:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, you can use its Model property in Datasource() to bind the data source.
4. Set AllowKeyboardNavigation to True to allow the grid to support keyboard interface
functionality.

View [ASPX]

<%=Html.Syncfusion().Syncfusion().Grid<MvcSampleApplication.Model
s.Order>("FlatGrid")
.Datasource(Model)
.AllowKeyboardNavigation(true)
.EnablePaging()
.EnableSorting()
%>

View [cshtml]

@{
Html.Syncfusion().Syncfusion().Grid<MvcSampleApplication.Models.Order>(
"FlatGrid")
.Datasource(Model)
.AllowKeyboardNavigation(true)
.EnablePaging()
.EnableSorting()
.Render();
}

5. Set its data source and render the view.

© 2014 Syncfusion. All rights reserved. 610 | Page


Essential Grid for ASP.NET MVC Classic

Controller

/// <summary>
/// Used for rendering the Grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{

var Data = new


StudentDataContext().AutoFormatStudent.Take(200);
return View(Data);
}

6. In order to work with paging and sorting actions, create a Post method for Index
actions and bind the data source to the grid as shown in the code given below.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{

var Data = new


StudentDataContext().AutoFormatStudent.Take(20);
return Data.GridActions<Student>();
}

7. Run the application. Keyboard shortcuts will be activated in the grid.

4.14.1.1.2 Through GridPropertiesModel


To enable keyboard interface using GridPropertiesModel:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the View.

View [ASPX]
<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Student>("Keyboar
d_Grid",(GridPropertiesModel<MvcSampleApplication.Models.Student>)ViewD
ata.Model) %>

© 2014 Syncfusion. All rights reserved. 611 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Student>("Keyboard_G
rid",(GridPropertiesModel<MvcSampleApplication.Models.Student>)ViewData
.Model))

4. Create a GridPropertiesModel in the Index method. Assign grid properties in this model
and pass the model from the controller to the view using the ViewData class as shown
below.

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{

var Data = new


StudentDataContext().AutoFormatStudent.Take(20);
GridPropertiesModel<Student> Keyboard_Grid = new
GridPropertiesModel<Student>()
{
DataSource = Data,
AllowKeyboardNavigation = true,
AllowPaging = true,
AllowSorting = true

};
ViewData.Model = Keyboard_Grid;
return View(Data);

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.

© 2014 Syncfusion. All rights reserved. 612 | Page


Essential Grid for ASP.NET MVC Classic

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{

IEnumerable data =new


StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}

6. Run the application. Keyboard shortcuts will be activated in the grid.

4.14.1.2 Configuring the Default Keys

The keyboard interface can be configured two ways:

 Through GridBuilder
 Through GridPropertiesModel

4.14.1.2.1 Through GridBuilder


To configure the keyboard interface using GridBuilder:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View). In the view, you
can use its Model property in Datasource() to bind the data source.
3. Set AllowKeyboardNavigation to True in order to allow the grid to support keyboard
interface.
4. Configure the keys for all the actions using the KeyConfigurator method. For example,
ExportToExcel and FocusKey actions are configured in the following code sample.

View [ASPX]

<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid")
.Datasource(Model)
.AllowKeyboardNavigation(true)
.KeyConfigurator(key => {
key.ExportToExcel(Keys.AltPlusA);
key.FocusKey(Keys.CtrlPlusAltPlusA);
})
.EnablePaging()
.EnableSorting()

%>

© 2014 Syncfusion. All rights reserved. 613 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("FlatGrid")
.Datasource(Model)
.AllowKeyboardNavigation(true)
.KeyConfigurator(key => {
key.ExportToExcel(Keys.AltPlusA);
key.FocusKey(Keys.CtrlPlusAltPlusA);
})
.EnablePaging()
.EnableSorting()
.Render();
}

5. Set the data source and render the view.

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{

var Data = new


StudentDataContext().AutoFormatStudent.Take(200);
return View(Data);
}

6. In order to work with paging and sorting actions, create a Post method for Index
actions and bind the data source to the grid as shown in the following code.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the
/// HtmlActionResult from the grid. The required response is
generated.

© 2014 Syncfusion. All rights reserved. 614 | Page


Essential Grid for ASP.NET MVC Classic

/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{

var Data = new


StudentDataContext().AutoFormatStudent.Take(20);
return Data.GridActions<Student>();
}

7. Run the application. Now FocusKey and ExportToExcel actions keyboard shortcuts
are configured.

4.14.1.2.2 Through GridPropertiesModel


To configure the keyboard interface using GridPropertiesModel:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Student>("Keyboar
d_Grid",(GridPropertiesModel<MvcSampleApplication.Models.Student>)ViewD
ata.Model) %>

View [cshtml]
@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Student>("Keyboard_G
rid",(GridPropertiesModel<MvcSampleApplication.Models.Student>)ViewData
.Model))

4. Create a GridPropertiesModel in the Index action. Assign grid properties in this model
and pass the model from the controller to the view using the ViewData class as shown in
the following code sample.
5. Configure the keys for all the actions using KeyConfigurator property. For example,
ExportToExcel and FocusKey actions are configured in the following code sample.

Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()

© 2014 Syncfusion. All rights reserved. 615 | Page


Essential Grid for ASP.NET MVC Classic

KeyConfigurator config = new KeyConfigurator();


config.ExportToExcel = Keys.AltPlusA;
config.FocusKey = Keys.CtrlPlusAltPlusA;

var Data = new


StudentDataContext().AutoFormatStudent.Take(20);
GridPropertiesModel<Student> Keyboard_Grid = new
GridPropertiesModel<Student>()
{
DataSource = Data,
AllowKeyboardNavigation = true,
KeyConfigurator = config
};
ViewData.Model = Keyboard_Grid;
return View(Data);

6. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}

7. Run the application. Now FocusKey and ExportToExcel actions keyboard shortcuts are
configured.

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > User Interaction > Keyboard Interface.

4.14.2 Tables for Properties, Methods, and Events


Properties

© 2014 Syncfusion. All rights reserved. 616 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Type Data Value it Dependency


of type accepts
prop
erty
AllowKeyboardNa Used to enable Server Boolean true/false NA
vigation KeyboardNavi side
gation.

KeyConfigurator Used to Server KeyConfigu KeyConfigu AllowKeyboardNa


customize all side rator rator object vigation
keyboard
shortcuts.

Name Description Type of Dat Value Dependency


property a it
Typ accep
e ts
FocusKey Used to set the Server side Keys Keys AllowKeyboardNavig
Keyboard options ation
shortcut for
FocusKey

FirstCellSelection Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
FirstCellSelectio
n

LastCellSelection Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
LastCellSelectio
n

FirstRowSelection Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
FirstRowSelecti
on

LastRowSelection Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
LastRowSelecti
on

© 2014 Syncfusion. All rights reserved. 617 | Page


Essential Grid for ASP.NET MVC Classic

InsertRecord Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
InsertRecord

DeleteRecord Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
DeleteRecord

EditRecord Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
EditRecord

SaveRequest Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
SaveRequest

CancelRequest Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
CancelRequest

ExportToExcel Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
ExportToExcel

NextPage Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for the
NextPage

PreviousPage Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for the
PreviousPage

NextPager Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
NextPager

© 2014 Syncfusion. All rights reserved. 618 | Page


Essential Grid for ASP.NET MVC Classic

PreviousPager Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
PreviousPager

LastPage Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for the
LastPage

FirstPage Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for the
FirstPage

SelectedGroupExp Used to set the Server side Keys Keys AllowKeyboardNavig


and Keyboard options ation
shortcut for
SelectedGroupE
xpand

TotalGroupExpand Used to set the Server side Keys Keys AllowKeyboardNavig


Keyboard options ation
shortcut for
TotalGroupExpa
nd

SelectedGroupColl Used to set the Server side Keys Keys AllowKeyboardNavig


apse Keyboard options ation
shortcut for
SelectedGroupC
ollapse

TotalGroupCollaps Used to set the Server side Keys Keys AllowKeyboardNavig


e Keyboard options ation
shortcut for
TotalGroupColla
pse

Keys Enumerable Options


The following options are present under the Keys Enumerable:
 Keys.Home
 Keys.End
 Keys.CtrlPlusHome
 Keys.CtrlPlusEnd

© 2014 Syncfusion. All rights reserved. 619 | Page


Essential Grid for ASP.NET MVC Classic

 Keys.PgUp
 Keys.PgDn
 Keys.Insert
 Keys.Delete
 Keys.Enter
 Keys.Esc
 Keys.F2
 Keys.CtrlPlusAltPlusF
 Keys.AltPlusHome
 Keys.AltPlusEnd
 Keys.AltPlusPgUp
 Keys.AltPlusPgDn
 Keys.AltPlusInsert
 Keys.AltPlusDelete
 Keys.AltPlusEnter
 Keys.AltPlusEsc
 Keys.CtrlPlusAltPlusHome
 Keys.CtrlPlusAltPlusEnd
 Keys.CtrlPlusAltPlusPgUp
 Keys.CtrlPlusAltPlusPgDn
 Keys.CtrlPlusAltPlusInsert
 Keys.CtrlPlusAltPlusDelete
 Keys.CtrlPlusAltPlusEnter
 Keys.CtrlPlusAltPlusEsc
 Keys.AltPlusA
 …
 Keys.AltPlusZ
 Keys.CtrlPlusAltPlusA
 …
 Keys.CtrlPlusAltPlusZ
 Keys.AltPlusUpArrow
 Keys.CtrlPlusAltPlusUpArrow
 Keys.AltPlusDownArrow
 Keys.CtrlPlusAltPlusDownArrow

Sample Link
To use the Keyboard Interface demo:
154. Select the Product Showcase option from the accordion on the left side of the sample
browser.
2. Select the Keyboard Interface demo.

© 2014 Syncfusion. All rights reserved. 620 | Page


Essential Grid for ASP.NET MVC Classic

4.15 Context Menu


The context menu support in Essential Grid for MVC improves user interaction by allowing you to
access the basic operations of the grid such as paging, sorting, grouping, filtering etc.
The context menu allows you to access the various basic functions of the grid and to customize it
with great ease by allowing you to add, remove, and clear the items.

The following figure gives you a basic idea of the structure and appearance of the context menu
in Essential Grid for MVC:

Figure 202: Grid with Context Menu in Header

4.15.1 Built-in Context Menu Items


Essential Grid for MVC context menu support provides the following built-in context menu items:
Context menu index
Context menu item Action
(zero based)

Item =
ContextMenuItems.AddRecord

HeaderCss = "addrecord"
0 Adds a new record to the grid.
TargetElement =
GridElements.Record
Text = "Add Record"

1 Edits the current record in the

© 2014 Syncfusion. All rights reserved. 621 | Page


Essential Grid for ASP.NET MVC Classic

Context menu index


Context menu item Action
(zero based)
Item = grid.
ContextMenuItems.EditRecord

HeaderCss = "editrecord"

TargetElement =
GridElements.Record
Text = "Edit Record"

Item =
ContextMenuItems.DeleteRecord

HeaderCss = "deleterecord"
Deletes the current record in
2 TargetElement = the grid.
GridElements.Record
Text = "Delete Record"

Item = ContextMenuItems.Save

HeaderCss = "save"

TargetElement = Calls the save request in the


3
GridElements.Record grid.
Text = "Save Request"

Item = ContextMenuItems.Cancel

HeaderCss = "cancel"

TargetElement = Calls the cancel request in


4
GridElements.Record the grid.
Text = "Cancel Request"

Item =
ContextMenuItems.SortByAsc

HeaderCss = "sortbyasc"
Sorts the column in
5 TargetElement = ascending order.
GridElements.ColumnHeader
Text = "Sort By Ascending"

© 2014 Syncfusion. All rights reserved. 622 | Page


Essential Grid for ASP.NET MVC Classic

Context menu index


Context menu item Action
(zero based)
Item =
ContextMenuItems.SortByDesc

HeaderCss = "sortbydesc"
Sorts the column in
6 TargetElement = descending order.
GridElements.ColumnHeader
Text = "Sort By Descending"

Item =
ContextMenuItems.ClearSorting

HeaderCss = "clearsorting"
Clears the sorting from the
7 TargetElement = GridElements. column in the grid.
ColumnHeader
Text = "Clear Sorting"

Item = ContextMenuItems.GroupBy

HeaderCss = "groupby"

8 TargetElement = Groups the column.


GridElements.ColumnHeader
Text = "Group By"

Item =
ContextMenuItems.ClearGrouping

HeaderCss = "cleargrouping"
Clears the grouping from the
9 TargetElement = GridElements. current column.
ColumnHeader
Text = "Clear Grouping"

Item = ContextMenuItems.Expand

HeaderCss = "expand"

TargetElement = Expands the current group in


10
GridElements.GroupCaption the grid.
Text = "Expand"

© 2014 Syncfusion. All rights reserved. 623 | Page


Essential Grid for ASP.NET MVC Classic

Context menu index


Context menu item Action
(zero based)
Item =
ContextMenuItems.Collapse

HeaderCss = "collapse"
Collapses the current column
11 TargetElement = GridElements. in the grid.
GroupCaption
Text = "Collapse"

Item =
ContextMenuItems.ClearFilter

HeaderCss = "clearfilter"
Clears the filtering descriptors
12 TargetElement = GridElements. from the column.
ColumnHeader
Text = "Clear Filter"

Item =
ContextMenuItems.HideColumn

HeaderCss = "hidecolumn"
13 TargetElement = GridElements. Hides the current column.
ColumnHeader
Text = "Hide column"

Item =
ContextMenuItems.NextPage

HeaderCss = "nextpage"
Navigates to the next page of
14 TargetElement = GridElements. the grid.
Pager
Text = "Next Page"

Item =
ContextMenuItems.PreviousPage
Navigates to the previous
15 HeaderCss = "previouspage" page of the grid.
TargetElement = GridElements.
Pager

© 2014 Syncfusion. All rights reserved. 624 | Page


Essential Grid for ASP.NET MVC Classic

Context menu index


Context menu item Action
(zero based)
Text = "Previous Page"

Item =
ContextMenuItems.LastPage

HeaderCss = "lastpage"
Navigates to the last page of
16 TargetElement = GridElements. the grid.
Pager
Text = "Last Page"

Item =
ContextMenuItems.FirstPage

HeaderCss = "firstpage"
Navigates to the first page of
17 TargetElement = GridElements. the grid.
Pager
Text = "First Page"

Item =
ContextMenuItems.NextPager

HeaderCss = "nextpager"
Navigates to the next pager of
18 TargetElement = GridElements. the grid.
Pager
Text = "Next Pager"

Item =
ContextMenuItems.PreviousPager

HeaderCss = "previouspager"
Navigates to the previous
19 TargetElement = GridElements. pager of the grid.
Pager
Text = "Previous Pager"

Item =
ContextMenuItems.RefreshPager It refreshes the pager of the
20
grid.
HeaderCss = "refreshpager"

© 2014 Syncfusion. All rights reserved. 625 | Page


Essential Grid for ASP.NET MVC Classic

Context menu index


Context menu item Action
(zero based)
TargetElement = GridElements.
Pager
Text = "Refresh Pager"

Item =
ContextMenuItems.VisibleColumns

HeaderCss = "columnheader" Gets or sets the visible


columns—this means you can
21 TargetElement = GridElements. choose which columns should
Pager be visible.
Text = "Visible Columns"

Enabling the Context Menu


You can enable the context menu through two ways:

4.15.1.1 Through GridBuilder


1. Create a model in the application.
2. Create a strongly typed view.
3. Call the EnableContextMenu method to enable the context menu in the grid.
View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.

----

%>

© 2014 Syncfusion. All rights reserved. 626 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]
@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.

----
.Render()

4. Set the data source and render the view

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
}

5. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code.

© 2014 Syncfusion. All rights reserved. 627 | Page


Essential Grid for ASP.NET MVC Classic

155.
Controller

<summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

6. Run the application. You can see the context menu as shown below in specified grid
elements.

Figure 203: Grid with Context Menu Items in the Header

© 2014 Syncfusion. All rights reserved. 628 | Page


Essential Grid for ASP.NET MVC Classic

Figure 204: Grid with Context Menu Items in Pager

Figure 205: Grid with Context Menu Items for Records

© 2014 Syncfusion. All rights reserved. 629 | Page


Essential Grid for ASP.NET MVC Classic

Figure 206: Grid with Context Menu in Expanded Group

4.15.1.2 Through GridPropertiesModel


1. Create a model in the application.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
})%>

View[cshtml]

@{Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>

© 2014 Syncfusion. All rights reserved. 630 | Page


Essential Grid for ASP.NET MVC Classic

{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
}).Render();
)}

4. Create a GridPropertiesModel in the Index action method.


5. To enable the context menu, set the EnableContextMenu to True as shown in the code
samples below:

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};

ViewData["GridModel"] = gridModel;
return View();
}

/// <summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

© 2014 Syncfusion. All rights reserved. 631 | Page


Essential Grid for ASP.NET MVC Classic

6. Run the application. You will be able to see the context menu as shown below:

Figure 207: Grid with Context Menu Items in the Header

© 2014 Syncfusion. All rights reserved. 632 | Page


Essential Grid for ASP.NET MVC Classic

Figure 208: Grid with Context Menu Items in the Pager

Figure 209: Grid with Context Menu Items for Records

Figure 210: Grid with Context Menu in Expanded Group


Sample Link
To view the samples, follow the steps below:

© 2014 Syncfusion. All rights reserved. 633 | Page


Essential Grid for ASP.NET MVC Classic

1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > User Interaction > Context Menu

4.15.2 Property, Method, and Event Tables


4.15.2.1 Property Tables

GridPropertiesModel Properties Table


Descripti Value it
Property Type of property Dependencies
on accepts

EnableContextMe Gets or bool  True NA


nu sets if the  False
context
menu is
enabled or
not

ContextMenuItem Gets or List<ContextMenuIte ContextMenuIte Depends on


s sets the ms> ms EnableContextMen
list of u—if
Context EnableContextMen
menu u is true,
items ContextMenuItems
will be displayed.

ContextMenuItem Properties Table

Type of Dependenc
Property Description Value it accepts
Property ies
Item Gets or sets ContextMenuIt ContextMenuItems.AddRecor NA
the ems d
ContextMenuIt
em
ContextMenuItems.EditReco
rd

ContextMenuItems.DeleteRe
cord

ContextMenuItems.Save

© 2014 Syncfusion. All rights reserved. 634 | Page


Essential Grid for ASP.NET MVC Classic

Type of Dependenc
Property Description Value it accepts
Property ies
ContextMenuItems.Cancel

ContextMenuItems.
SortByAsc

ContextMenuItems.SortByDe
sc

ContextMenuItems.ClearSor
ting

ContextMenuItems.GroupBy

ContextMenuItems.
ClearGrouping

ContextMenuItems.Expand

ContextMenuItems.Collapse

ContextMenuItems.ClearFil
ter

ContextMenuItems.HideColu
mn

ContextMenuItems.NextPage

ContextMenuItems.Previous
Page

ContextMenuItems.LastPage

ContextMenuItems.FirstPag
e

© 2014 Syncfusion. All rights reserved. 635 | Page


Essential Grid for ASP.NET MVC Classic

Type of Dependenc
Property Description Value it accepts
Property ies

ContextMenuItems.NextPage
r

ContextMenuItems.Previous
Pager

ContextMenuItems.RefreshP
ager

ContextMenuItems.VisibleC
olunms

HeaderCss It gets or sets string Any form of String NA


the Css of the
ContextMenuIt
em Header

TargetElem Gets or sets GridElements GridElements.All NA


ent the target
GridElements.Record
element to
which the GridElements.Pager
context menu GridElements.ColumnHeader
item belongs
GridElements.GroupCaption

Text Gets or sets string Any form of string NA


the text of the
Context menu
items

4.15.2.2 Methods
Name Description Arguments
EnableContextMenu Enables the Context NA
Menu

ContextMenuItems Customizes the Context Action<ContextMenuItemsBuilder>


menu items

© 2014 Syncfusion. All rights reserved. 636 | Page


Essential Grid for ASP.NET MVC Classic

4.15.2.3 Client-Side Events


Event Description Arguments Type
OnContextMenuOpen Gets or sets the Handler Sender > Grid NA
name of the
Args > EventArgs
OnContextMenuOpen event

OnContextMenuClose Gets or sets the Handler Sender > Grid NA


name of the
Args > EventArgs
OnContextMenuClose event

OnContextMenuItemClick Gets or sets the Handler Sender > Grid NA


name of the
Args > EventArgs
OnContextMenuItemClick
event

OnBeforeContextMenuOpen Gets or sets the Handler Sender > Grid NA


name of the
Args > EventArgs
OnBeforeContextMenuOpen
event

4.15.3 Customizing the Context Menu


Customizing the context menu can be done in two ways.

4.15.3.1 Through GridBuilder


1. Create a model in the application.
2. Create a strongly typed View.
3. Call the EnableContextMenu method to enable the context menu in the grid.
4. Add the new context menu items using the Add method in the ContextMenuItems builder
as shown in the following code samples:

View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order

© 2014 Syncfusion. All rights reserved. 637 | Page


Essential Grid for ASP.NET MVC Classic

Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {

items.Add(new ContextMenuItem() { Item =


ContextMenuItems.Custom, HeaderCss = "PDFExport", TargetElement =
GridElements.All, Text = "Export to PDF" });
items.Add(new ContextMenuItem() { Item =
ContextMenuItems.Custom, HeaderCss = "WordExport", TargetElement =
GridElements.Record, Text = "Export to Word" });
items.Add(new ContextMenuItem() { Item =
ContextMenuItems.Custom, HeaderCss = "ExcelExport", TargetElement =
GridElements.Record, Text = "Export to Excel" });

})

----

%>

View[cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {

items.Add(new ContextMenuItem() { Item =


ContextMenuItems.Custom, HeaderCss = "PDFExport", TargetElement =
GridElements.All, Text = "Export to PDF" });
items.Add(new ContextMenuItem() { Item =

© 2014 Syncfusion. All rights reserved. 638 | Page


Essential Grid for ASP.NET MVC Classic

ContextMenuItems.Custom, HeaderCss = "WordExport", TargetElement =


GridElements.Record, Text = "Export to Word" });
items.Add(new ContextMenuItem() { Item =
ContextMenuItems.Custom, HeaderCss = "ExcelExport", TargetElement =
GridElements.Record, Text = "Export to Excel" });

})

----
.Render()

5. Remove the built-in items using the RemoveMatchedItems method in the


ContextMenuItems builder as shown in the following code samples:

View[ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {

items.RemoveMatchedItems(it => it.Item ==


ContextMenuItems.RefreshPager); // Removed Refresh Pager context menu
item.
})

----

%>

© 2014 Syncfusion. All rights reserved. 639 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {
items.RemoveMatchedItems(it => it.Item ==
ContextMenuItems.RefreshPager); // Removed Refresh Pager context menu
item.

})

----
.Render()

6. You can also clear all the context menu items using the Clear method in the
ContextMenuItems builder as shown in the code samples below.
View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");

© 2014 Syncfusion. All rights reserved. 640 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p => p.OrderDate).HeaderText("Order


Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {

items.Clear() // Cleared all built-in items.


})

----

%>

View[cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
----
.EnableContextMenu() // Enabling the context menu.
.ContextMenuItems(items => {
items.Clear() // Cleared all built-in items.

})

----
.Render()

7. Set the data source and render the view

© 2014 Syncfusion. All rights reserved. 641 | Page


Essential Grid for ASP.NET MVC Classic

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);
}

8. In order to work with filter actions, create a Post method for Index actions and bind the data
source to the grid as shown in the following code.
Controller

<summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

9. Run the application.

© 2014 Syncfusion. All rights reserved. 642 | Page


Essential Grid for ASP.NET MVC Classic

Figure 211: Grid with Custom Items in the Context Menu

4.15.3.2 Through GridPropertiesModel


1. Create a model in the application.
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View[ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
})%>

View[cshtml]

@{Html.Syncfusion().Grid<Order>("Grid1", "GridModel", column =>


{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order

© 2014 Syncfusion. All rights reserved. 643 | Page


Essential Grid for ASP.NET MVC Classic

Date").Format("{OrderDate:dd/MM/yyyy}");
column.Add(p => p.Freight).HeaderText("Price").Format("{0:c}");
}).Render();
)}

4. Create a GridPropertiesModel in the Index action.


5. To enable the context menu, set the EnableContextMenu to True as shown in the code
samples below:

Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};

ViewData["GridModel"] = gridModel;
return View();
}

/// <summary>
/// Paging/editing/filtering requests are mapped to this
method. This method invokes the HtmlActionResult
/// from the grid and the required response is generated.
/// </summary>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();

6. To add custom context menu items:

© 2014 Syncfusion. All rights reserved. 644 | Page


Essential Grid for ASP.NET MVC Classic

156.
Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};
gridModel.ContextMenuItems.Add(new ContextMenuItem() { Item =
ContextMenuItems.Custom, HeaderCss = "PDFExport", TargetElement =
GridElements.All, Text = "Export to PDF" });
gridModel.ContextMenuItems.Add(new ContextMenuItem() { Item
= ContextMenuItems.Custom, HeaderCss = "WordExport", TargetElement =
GridElements.Record, Text = "Export to Word" });
gridModel.ContextMenuItems.Add(new ContextMenuItem() { Item
= ContextMenuItems.Custom, HeaderCss = "ExcelExport", TargetElement =
GridElements.Record, Text = "Export to Excel" });

ViewData["GridModel"] = gridModel;
return View();
}

7. To remove custom menu items, remove all methods providing predicates as the argument
as shown in the code below:
Controller
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",

© 2014 Syncfusion. All rights reserved. 645 | Page


Essential Grid for ASP.NET MVC Classic

EnableContextMenu = true,
-----
};
gridModel.ContextMenuItems.RemoveAll(c => c.Item ==
ContextMenuItems.AddRecord);

ViewData["GridModel"] = gridModel;
return View();
}

8. To clear the custom items in the Context menu, clear methods in the Context menu list as
shown in the code samples below:
157.
Controller

/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200).ToList(),
Caption = "Orders",
EnableContextMenu = true,
-----
};
gridModel.ContextMenuItems.Clear();

ViewData["GridModel"] = gridModel;
return View();
}

9. Run the application. You will be able to see the context menu as shown below:

© 2014 Syncfusion. All rights reserved. 646 | Page


Essential Grid for ASP.NET MVC Classic

Figure 212: Grid with Custom Items in the Context Menu

4.16 Appearance
4.16.1 Built-in Skin Styles
The Grid control has some predefined skins which can be controlled through a single property
setting.

Some of the available skins are as follows:


 Office 2007 Blue
 Office 2007 Black
 Office 2007 Silver
 Vista
 Almond
 Blend
 Blueberry
 Marble
 Metro
 Midnight
 Monochorome
 Olive
 Sandune
 Turquoise
 VS2010

Properties

© 2014 Syncfusion. All rights reserved. 647 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it accepts Any other


property dependencies/sub-
properties
associated
AutoFormat Used to apply Enum Skins.Office2007Blue NA
auto format by
Skins.Office2007Black
using Skins
enumeration. Skins.Office2007Silver
Default value is Skins.Vista
Office2007Blue.
Skins.Almond

Skins.Blend
Skins.Blueberry
Skins.Marble

Skins.Metro
Skins.Midnight

Skins.Monochrome
Skins.Olive

Skins.Sandune
Skins.Turquoise

Skins.VS2010

Methods

Method Parameters Return type Descriptions


AutoFormat (Skins) Skins IGridBuilder<T> Used to set skins to grid.

4.16.1.1 Through GridBuilder


158. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view create the Grid control and configure its properties.
159.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)

© 2014 Syncfusion. All rights reserved. 648 | Page


Essential Grid for ASP.NET MVC Classic

.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.ShipCity).HeaderText("Ship City");
})
.EnablePaging()
.EnableSorting()
%>

160.
View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(P =>
P.ShipCountry).HeaderText("Ship Country");
column.Add(p =>
p.ShipCity).HeaderText("Ship City");
})
.EnablePaging()
.EnableSorting()
.Render();
}

4. Specify the skin name using the AutoFormat() method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
………
………

© 2014 Syncfusion. All rights reserved. 649 | Page


Essential Grid for ASP.NET MVC Classic

.AutoFormat(Skins.Almond)
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
………
………
.AutoFormat(Skins.Almond)
.Render();
}

5. Run the application. The grid will appear as shown below.

Figure 213: Grid with Almond Skin

4.16.1.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel", column=> {
column.Add(p =>

© 2014 Syncfusion. All rights reserved. 650 | Page


Essential Grid for ASP.NET MVC Classic

p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(P => P.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipCity).HeaderText("Ship
City");
})%>

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Orders_Grid","GridModel",
column=> {
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.OrderID).HeaderText("Order
ID");
column.Add(P => P.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.ShipCity).HeaderText("Ship
City");
}))

3. Create a GridPropertiesModel in the Index method. Assign grid properties in this


model.
161.
Controller

GridPropertiesModel<Order> model = new


GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(500),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true
};

4. Specify the skin name using the AutoFormat property and pass the model to the view
using the ViewData() method.

Controller

GridPropertiesModel<Order> model = new


GridPropertiesModel<Order>()
{
DataSource = new

© 2014 Syncfusion. All rights reserved. 651 | Page


Essential Grid for ASP.NET MVC Classic

NorthwindDataContext().Orders.Take(500),
Caption = "Orders",
AllowPaging = true,
AllowSorting = true,
AutoFormat = Skins.Almond

};
ViewData["GridModel"] = model;

5. Run the application. The grid will appear as shown below.

Figure 214: Grid with Almond Skin


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Apperance > Built-in Skins

4.16.2 Customizing the Grid Appearance


The Grid control allows you to customize its appearance by using the Theme studio.
The Theme Studio allows you to customizing the appearance of the grid easily by applying the
css in the theme builder and see the immediate changes in the application(Grid). And also you
can customize the sprite images of the grid.

Note: Theme Builder is included from Essential Studio version 11.1.0.21

Properties

© 2014 Syncfusion. All rights reserved. 652 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependencies/sub-
properties
associated
CustomCss Used to specify CSS class name which string Any style NA
can be applied to the Grid. This class
property settings overrides auto name
formatting.

Methods

Method Parameters Return type Descriptions


CustomCss ClassName in IGridBuilder<T> Used to specify CSS class name which
(className) string format can be applied to the Grid. This property
settings overrides auto formatting.

4.16.2.1 Through GridBuilder

In order to work with this feature please follow the steps below:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view create the Grid control and configure its properties.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}) .EnableSorting()
.EnablePaging()
.EnableLegacySettings(true)

© 2014 Syncfusion. All rights reserved. 653 | Page


Essential Grid for ASP.NET MVC Classic

.CustomCss("Syncfusion-Grid-Greenish")

%>

162.
View [cshtml]

@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}) .EnableSorting()
.EnablePaging()
.EnableLegacySettings(true)

.Render();
}

4. Open the grid online sample browser by using the below link
163. Online sample Link: http://mvc.syncfusion.com/demos/ui/grid

© 2014 Syncfusion. All rights reserved. 654 | Page


Essential Grid for ASP.NET MVC Classic

Figure 215: Online sample browser for grid


164.
5. Click the Theme Studio Beta Button which is in the right corner of the sample browser.

© 2014 Syncfusion. All rights reserved. 655 | Page


Essential Grid for ASP.NET MVC Classic

Figure 216: Theme Studio


165.
6. Select Grid from the drop down button. And select any theme that you want to
customize from the Gallery. In this case you have to change the “Almond” skin to the
“Greenish” skin.

Figure 217: Click the Gallery button the Basic themes are loaded

© 2014 Syncfusion. All rights reserved. 656 | Page


Essential Grid for ASP.NET MVC Classic

7. Select the Almond skin from the Basic Themes tab.

Figure 218: Almond skin for the Grid

8. Apply your css in the left hand side accordion and see the changes in the grid.
9. In this case, we have customized the grid and download the css and sprite images for
the “Greenish” skin using the download button which is in the right corner of the theme
studio.

© 2014 Syncfusion. All rights reserved. 657 | Page


Essential Grid for ASP.NET MVC Classic

Figure 219: Download skin dialog box

10. Enter the skin name “Greenish” in the Skin Name text box.
11. Select Grid checkbox and click Download Zip button.
166.

Note: If you want the css of the sub controls of the grid then check the Tools check box also.
167. Download Zip File:
http://www.syncfusion.com/Downloads/Support/Online%20Document%20Uploads/ASP
NET-MVC/sfThemes.zip
168.
12. Add the new custom CSS and sprite image in the application and add this custom CSS
in the master page as demonstrated below:

[Site.Master]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent"
runat="server" /></title>
<link href="<%=
Url.Content("~/Content/CustomCss/Syncfusion-Grid-Greenish.css")%>"
rel="stylesheet"
type="text/css" />
……………
……………

© 2014 Syncfusion. All rights reserved. 658 | Page


Essential Grid for ASP.NET MVC Classic

</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent"
runat="server" /></title>
<link href="@Url.Content("~/Content/CustomCss/Syncfusion-
Grid-Greenish.css")" rel="stylesheet" type="text/css" />
……………
……………
</head>

13. Specify the custom CSS class name using the CustomCss() method. In this case
“Syncfusion-Grid-Greenish” is the custom CSS class name.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(.Column(column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}) .EnableSorting()
.EnablePaging()
.EnableLegacySettings(true)
.CustomCss("Syncfusion-Grid-Greenish")
%>

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.Column(.Column(column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee

© 2014 Syncfusion. All rights reserved. 659 | Page


Essential Grid for ASP.NET MVC Classic

ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}) .EnableSorting()
.EnablePaging()
.EnableLegacySettings(true)
.CustomCss("Syncfusion-Grid-Greenish")
.Render();
}

14. Run the application. The grid will appear as shown below.

Figure 220: Grid with Custom Skin—Greenish

4.16.2.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]

<%=Html.Syncfusion().Grid<MVCSampleBrowser.Models.Order>(
"CustomCSS_Grid", "GridModel",
column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);

© 2014 Syncfusion. All rights reserved. 660 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(p => p.EmployeeID).HeaderText("Employee


ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
})%>

View [cshtml]

@(Html.Syncfusion().Grid<MVCSampleBrowser.Models.Order>(
"CustomCSS_Grid", "GridModel",
column =>
{
column.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(90);
column.Add(P => P.ShipCountry).HeaderText("Ship
Country").Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}").Width(120);
}))

4. Create a GridPropertiesModel in the Index method. Assign grid properties in this


model.

Controller

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.ToList(),
AllowSorting = true,
Caption = "Orders",
AllowPaging=true,
EnableLegacySettings=true,
CustomCss = "Syncfusion-Grid-Greenish"
};

© 2014 Syncfusion. All rights reserved. 661 | Page


Essential Grid for ASP.NET MVC Classic

5. Open the grid online sample browser by using the below link
169. Online sample Link: http://mvc.syncfusion.com/demos/ui/grid

Figure 221: Online sample browser for grid


170.
6. Click the Theme Studio Beta Button which is in the right corner of the sample browser.
171.

© 2014 Syncfusion. All rights reserved. 662 | Page


Essential Grid for ASP.NET MVC Classic

Figure 222: Theme Studio


172.
7. Select Grid from the drop down button. And select any theme that you want to
customize from the Gallery. In this case you have to change the “Almond” skin to the
“Greenish” skin
173.

© 2014 Syncfusion. All rights reserved. 663 | Page


Essential Grid for ASP.NET MVC Classic

Figure 223: Click the Gallery button the Basic themes are loaded

174.
8. Select the Almond skin from the Basic Themes tab.
175.

Figure 224: Almond skin for the Grid

© 2014 Syncfusion. All rights reserved. 664 | Page


Essential Grid for ASP.NET MVC Classic

9. Apply your CSS in the left hand side accordion and see the changes in the grid.
10. In this case, we have customized the grid and download the css and sprite images for
the “Greenish” skin using the download button which is in the right corner of the theme
studio.

Figure 225: Download skin dialog box


11. Enter the skin name “Greenish” in the Skin Name text box.
12. Select Grid checkbox and click Download Zip button.
176.

Note: If you want the css of the sub controls of the grid then check the Tools check box also.
177. Download Zip File:
http://www.syncfusion.com/Downloads/Support/Online%20Document%20Uploads/ASP
NET-MVC/sfThemes.zip

178.
13. Add the new custom CSS and sprite image to the application and add this custom CSS
in the master page as shown below:

[Site.Master]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent"
runat="server" /></title>

© 2014 Syncfusion. All rights reserved. 665 | Page


Essential Grid for ASP.NET MVC Classic

<link href="<%=
Url.Content("~/Content/CustomCss/Syncfusion-Grid-Greenish.css")%>"
rel="stylesheet" type="text/css" />
……………
……………
</head>

[_Layout.cshtml]

<head runat="server">
<title><asp:ContentPlaceHolder ID="TitleContent"
runat="server" /></title>
<link href="@Url.Content("~/Content/CustomCss/Syncfusion-
Grid-Greenish.css")" rel="stylesheet" type="text/css" />
……………
……………
</head>

14. Specify the custom CSS class name using the CustomCss property and pass the
model to the view using the ViewData() method.

Controller

GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Order>()


{
DataSource = new
NorthwindDataContext().Orders.ToList(),
AllowGrouping = true,
AllowSorting = true,
Caption = "Orders",
AllowPaging=true,
EnableLegacySettings=true,
AllowScrolling=false,
AllowDragAndDrop=true,
Height=225,
CustomCss = "Syncfusion-Grid-Greenish"
};
ViewData["GridModel"] = model;

15. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 666 | Page


Essential Grid for ASP.NET MVC Classic

Figure 226: Grid with Custom Skin—Greenish


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Apperance > Custom Skin

4.17 Localization
Localization is the process of customizing the user interface (UI) as locale-specific in order to
display regional data i.e. in a language and culture specific to a particular country or region. This
is done with the help of localized resources by the control. Essential Grid provides inherent
support to localize its UI.

Use Case Scenarios


Localization helps to provide IT solutions to global customers in their native languages.

© 2014 Syncfusion. All rights reserved. 667 | Page


Essential Grid for ASP.NET MVC Classic

Figure 227: Grid With French Localization

4.17.1 Adding Localization to an Application

4.17.1.1 Through GridBuilder

To enable the localization feature using GridBuilder:

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create a folder named App_GlobalResources in the application and create your own
localization resource (.resx) file in this folder.

Figure 228: App_GlobalResource Folder

© 2014 Syncfusion. All rights reserved. 668 | Page


Essential Grid for ASP.NET MVC Classic

In order to create a new localization resource file, download the default localization file from the
following location, rename it, and then use Visual Studio to edit the values.

GridResource.zip

The default English localization file is shown in the following screenshot:

Figure 229: Resource File For English Localization

Note: The name of the localization file should be in the format GridResource.[culture].resx. For
example: "GridLocalization.fr-FR.resx"

4. Create the Grid control in the view and configure its properties.
179. There are two ways to specify the culture information, namely:

 Setting the CurrentUICulture property of the CurrentThread inside your Action method:

© 2014 Syncfusion. All rights reserved. 669 | Page


Essential Grid for ASP.NET MVC Classic

[Controller]
public ActionResult Index()
{

System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Glo


balization.CultureInfo("fr-FR");
var data = new NorthwindDataContext().Orders;
return View(data);
}

 Specifying the culture using the Localize() method:

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Localize("fr-FR")// Specify the culture code.
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");

columns.Add(P => P.ShipCountry).HeaderText("Ship Country");


columns.Add(p => p.OrderDate).HeaderText("Order Date").Forma
t("{0:dd-MM-yyyy}");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableSorting()
.EnableFiltering()
.AutoFormat(Skins.Sandune)
.Localize("fr-FR")// Specify the culture code.
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");

© 2014 Syncfusion. All rights reserved. 670 | Page


Essential Grid for ASP.NET MVC Classic

columns.Add(p => p.CustomerID).HeaderText("Customer ID");


columns.Add(p => p.EmployeeID).HeaderText("Employee ID");

columns.Add(P => P.ShipCountry).HeaderText("Ship Country");


columns.Add(p => p.OrderDate).HeaderText("Order Date").Forma
t("{0:dd-MM-yyyy}");
}).Render();
}

5. Set its data source and render the View.

[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}

6. Enable the globalization in the layout/master page.


[Site.Master]
<body>
......
......

<%=Html.Syncfusion().ScriptManager().EnableGlobalization().Render();%>
</body>

[_Layout.cshtml]
<body>
......
......

@{Html.Syncfusion().ScriptManager().EnableGlobalization().Render();}
</body>

7. Run the application. The grid will appear as shown below:

© 2014 Syncfusion. All rights reserved. 671 | Page


Essential Grid for ASP.NET MVC Classic

Figure 230: Grid With French Localization

4.17.1.1.1 Customization

If you want to customize the localization resource file folder path, then use the
LocalizationPath() method.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Localize("fr-FR")// Specify the culture code.
.LocalizationPath("~/App_LocalResources") // Specify the folder.
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Localize("fr-FR")// Specify the culture code.

.LocalizationPath("~/App_LocalResources") // Specify the folder.


.Render();
}

© 2014 Syncfusion. All rights reserved. 672 | Page


Essential Grid for ASP.NET MVC Classic

4.17.1.2 Through GridPropertiesModel


To enable localization feature using GridPropertiesModel:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create a folder named App_GlobalResources in your application and create your own
localization resource (.resx) file in this folder.

Figure 231: App_GlobalResource Folder

In order to create a new localization resource file, download the default localization file from the
following location, rename it, and then use Visual Studio to edit the values.

GridResource.zip

The default English localization file is shown in the following screenshot:

© 2014 Syncfusion. All rights reserved. 673 | Page


Essential Grid for ASP.NET MVC Classic

Figure 232: Resource File For English Culture

Note: The name of the localization file should be in the format GridResource.[culture].resx. For
example: "GridLocalization.fr-FR.resx"

4. Add the following code in the Index.aspx file to create the Grid control in the view.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
})%>

© 2014 Syncfusion. All rights reserved. 674 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]
@( Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order Date");
}))

5. There are two ways to specify the culture information:

 Setting the CurrentUICulture property of the CurrentThread inside your Action method.

[Controller]
public ActionResult Index()
{

System.Threading.Thread.CurrentThread.CurrentUICulture = new System.Glo


balization.CultureInfo("fr-FR");
}

 Creating a GridPropertiesModel in the Index method. Use the Localize property to


specify the culture details:

[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AllowPaging = true,
AllowFiltering = true,
AutoFormat = Skins.Sandune,
Localize="fr-FR" // specify Culture code
};
ViewData["GridModel"] = gridModel;
return View();
}

6. Enable the globalization in the layout/master page.

© 2014 Syncfusion. All rights reserved. 675 | Page


Essential Grid for ASP.NET MVC Classic

[Site.Master]
<body>
......
......

<%=Html.Syncfusion().ScriptManager().EnableGlobalization().Render();%>
</body>

[_Layout.cshtml]
<body>
......
......

@{Html.Syncfusion().ScriptManager().EnableGlobalization().Render();}
</body>

7. Run the application. The grid will appear as shown in the following screenshot:

Figure 233: Grid with French Localization

4.17.1.2.1 Customization
If you want to customize the localization resource files folder path use the LocalizationPath
property.

[Controller]
public ActionResult Index()
{
GridPropertiesModel<Order> gridModel = new GridPropertiesModel<Or
der>()
{
DataSource = new NorthwindDataContext().Orders,

© 2014 Syncfusion. All rights reserved. 676 | Page


Essential Grid for ASP.NET MVC Classic

Caption = "Orders",
AllowPaging = true,
AllowFiltering = true,
AutoFormat = Skins.Sandune,
Localize="fr-FR", // Specify culture code.
LocalizationPath="~/App_LocalResources"//
Specify the folder path.
};
ViewData["GridModel"] = gridModel;
return View();
}

Tables for Properties, Methods, and Events


Properties

Property Description Type Data type Reference


links
Localize Get or set the Server side A string NA
localization containing the
culture of Grid name of the target
System.Globalizat
ion.CultureInfo

LocalizationPath Get or set the Server side Any string value. Localize
localization
Default:
resource path of
“~/App_GlobalRe
the resource file
sources”
location

Methods

Method Descripti Parameters Type Return Reference links


on Type
Localize Used to (string culture) Server- Void NA
specify the side
localization
culture of
grid.

© 2014 Syncfusion. All rights reserved. 677 | Page


Essential Grid for ASP.NET MVC Classic

Localization Used to (string path) Server- Void Localize


Path configure side
the
localization
resource file
path

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Localization > Localization

4.18 Hierarchical Grid


Hierarchical Grid
With the hierarchical grid feature, Essential Grid for MVC can display hierarchical relationships.
Such relationships can be manually set up between multiple grids.
The records involved in these hierarchical relationships can be synchronized to update changes
in all records whenever changes are made to one record. The parent records are expandable and
collapsible. All records with nested relationships can be expanded to reveal the underlying
detailed record which can be achieved by clicking the expand/collapse icons.
Use Case Scenarios
You can secure employee details along with the employee hierarchy of the company.
Hierarchical Grid Application

4.18.1 Server Mode


4.18.1.1 Through GridBuilder
Perform the following steps to create a hierarchical grid through GridBuilder in server mode:
1.
Create a model in the application (refer to How to > Adding model to the application).
2.
Create a strongly typed view (refer to How to > strongly typed view).
3.
Create the Grid control in the view and configure the properties.
4.
Use the ChildGrid method as shown below.
5.
The Mappers Action method for the child grid should contain the Foreign Key to relate
to the Parent.
6. It should end with the method ToChildGridTemplate.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")

© 2014 Syncfusion. All rights reserved. 678 | Page


Essential Grid for ASP.NET MVC Classic

.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<Order_Detail>("ChildGrid
_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
%>

7. For Razor, use the code shown below:

View[cshtml]

@{
Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<
Order_Detail>("ChildGrid_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the
parent grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})

.ToChildGridTemplate());

© 2014 Syncfusion. All rights reserved. 679 | Page


Essential Grid for ASP.NET MVC Classic

})
.Render();
}

8. Set its data source and render the view.

[Controller]

public ActionResult Index()


{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);

9. In order to work with paging actions, create a post method for the index action and bind
the data source to the grid as shown in the following code:

[Controller]
/// <summary>
/// Paging action mapper, Paging Request is mapped here
/// </summary>
/// <param name="args">Contains Paging Information.</param>
/// <returns>HtmlActionResult which returns data displayed on
the Grid</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext
().Orders.Take(60).ToList();
return data.GridActions<Order>();
}

10. In order to work with the child grid, create a post method for the child grid and bind the
data source to the child grid as shown in the following code:
[Controller]
[AcceptVerbs(HttpVerbs.Post)]

public ActionResult ChildGrid(PagingParams args, int? OrderID)


{
IEnumerable data = new NorthwindDataContext
().Order_Details.Where(c=>c.OrderID == OrderID).ToList();
return data.GridActions<Order_Detail>();
}

11. Run the application. The grid will appear as shown below:

© 2014 Syncfusion. All rights reserved. 680 | Page


Essential Grid for ASP.NET MVC Classic

Figure 234: Hierarchical grid in server mode through GridBuilder


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Hierarchy > Server Mode

4.18.2 JSON Mode


4.18.2.1 Through GridBuilder

Perform the following steps to create a hierarchical grid through GridBuilder in JSON mode:

1.Create a model in the application (refer to How to > Adding model to the application).
2.Create the Grid control in the view and configure the properties.
3.Use the ChildGrid method as shown below.
4.The Mappers Action method for the child grid should contain the Foreign Key to relate
to the Parent.
5. It should end with the method ToChildGridTemplate.
View[ASPX]
<%=Html.Syncfusion().Grid<EmployeeView>("GridSrc")
.Caption("Employee Grid")

© 2014 Syncfusion. All rights reserved. 681 | Page


Essential Grid for ASP.NET MVC Classic

.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent grid
as a unique ID for the child grid.
grid.child.ChildGridTemplate(Html.Syncfusion().Grid<OrdersView>("ChildG
rid_${EmployeeID}")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("JSONChildGrid", new {
EmployeeID = "${ EmployeeID}" });
})
.ToChildGridTemplate());
})
%>

6. For Razor, the code is given below:

View[cshtml]
@{
Html.Syncfusion().Grid<EmployeeView>("GridSrc")
.Datasource(Model)
.Caption("Employee Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<OrdersView>("ChildGrid_$
{EmployeeID}").
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("JSONChildGrid", new {
EmployeeID = "${ EmployeeID}" });
})
.ToChildGridTemplate());
})
.Render(); }

7. Set its data source and render the view.

© 2014 Syncfusion. All rights reserved. 682 | Page


Essential Grid for ASP.NET MVC Classic

[Controller]
public ActionResult Index()
{
return View();

8. In order to work with paging actions, create a post method for the index action and bind
the data source to the grid as given in the following code sample.

[Controller]
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page displays the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
var ordersData = new
NorthwindDataContext().EmployeeViews.ToList();
return ordersData.GridJSONActions<EmployeeView>();
}

9. In order to work with the child grid, create a post method for the child grid and bind the
data source to the child grid as shown in the following code:
[Controller]
/// <summary>
/// Used to bind the child grid.
/// </summary>
/// <returns>View page displays the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult JSONChildGrid(PagingParams args, string
EmployeeID)
{
IEnumerable data = new
NorthwindDataContext().OrdersViews.Where(c => c.EmployeeID ==
EmployeeID).ToList();
return data.GridJSONActions<OrdersView>();
}

10. Run the application. The grid will appear as shown below:

© 2014 Syncfusion. All rights reserved. 683 | Page


Essential Grid for ASP.NET MVC Classic

Figure 235: Hierarchical grid in JSON mode through GridBuilder

Tables for Properties, Methods, and Events

Properties

Property Description Type Data Type Reference links


ChildGrid Sets the child grid if Server Side String NA
the hierarchical grid
is needed.

Methods
Method Description Parameters Type Return Reference
Type links
Sets the child
ChildGrid grid if the
String IGridBuilder NA
hierarchical
grid is needed.

© 2014 Syncfusion. All rights reserved. 684 | Page


Essential Grid for ASP.NET MVC Classic

ChildGridTem
plate (to
Renders the render the
ToChildGridTe ChildGridTem
grid in child child grid, the
mplate plate NA
grid template user has to
format. render the grid
as this type).

Events
Event Description Arguments Type Reference links

This event occurs in String handler


OnRecordExp Client-Side NA
every master row
anded
expanded event.

This event occurs in String handler


OnRecordColl Client-Side NA
every master row
apsed
collapsed event.

This event occurs String handler


OnRecordExp Client-Side NA
before every master
anding
row expands.

This event occurs String handler


OnRecordColl Client-Side NA
before every master
apsing
row collapses.

Using Client-Side Events

Using the OnRecordCollapsing event, users can avoid a collapse event. Using the
OnRecordExpanding event, users can avoid an expand event.

The client-side events are used in ASPX as shown below in server mode through GridBuilder.
View[ASPX]
<%=Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)

© 2014 Syncfusion. All rights reserved. 685 | Page


Essential Grid for ASP.NET MVC Classic

.ClientSideEvents(eve =>
{

eve.OnRecordCollapsing("OnRecordCollapsing");
eve.OnRecordExpanding("OnRecordExpanding");
eve.OnRecordCollapsed("OnRecordCollapsed");
eve.OnRecordExpanded("OnRecordExpanded");
})

.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<Order_Detail>("ChildGrid
_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
%>

For Razor, use the code shown below in server mode through GridBuilder.
View[cshtml]
@{
Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ClientSideEvents(eve =>
{

eve.OnRecordCollapsing("OnRecordCollapsing");
eve.OnRecordExpanding("OnRecordExpanding");
eve.OnRecordCollapsed("OnRecordCollapsed");
eve.OnRecordExpanded("OnRecordExpanded");
})
.ChildGrid(child =>
{

child.ChildGridTemplate(Html.Syncfusion().Grid<
Order_Detail>("ChildGrid_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>

© 2014 Syncfusion. All rights reserved. 686 | Page


Essential Grid for ASP.NET MVC Classic

{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
.Render();
}

[Javascript]

<script type="text/javascript">
function OnRecordCollapsing(sender, args) {
// perform any action during the record is collapsing.
}

function OnRecordExpanding(sender, args) {


// perform any action during the record is expanding.
}
function OnRecordCollapsed(sender, args) {
// perform any action when the record is collapsed.
}
function OnRecordExpanded(sender, args) {
// perform any action when the record is expanded.
}
</script>

Appearance

© 2014 Syncfusion. All rights reserved. 687 | Page


Essential Grid for ASP.NET MVC Classic

Figure 236: Hierarchical Grid


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Hierarchy > JSON Mode

4.18.3 Editing
4.18.3.1 Server Mode

4.18.3.1.1 Through GridBuilder


Perform the following steps to create a hierarchical grid through GridBuilder in server mode:

1. Create a model in the application (refer to How to > Adding model to the application).
2. Create a strongly typed view (refer to How to > strongly typed view).
3. Create the Grid control in the view and configure their properties.
4. Use the ChildGrid method as shown below.
5. The Mappers Action method for the child grid should contain the Foreign Key to relate to
the Parent.
6. It should end with the method ToChildGridTemplate.

© 2014 Syncfusion. All rights reserved. 688 | Page


Essential Grid for ASP.NET MVC Classic

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =
"${OrderID}" });
})
.ToChildGridTemplate());
})
%>

7. For Razor, use the code shown below:


View[cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Mappers(map =>
{
// Specify the foreign key related to the
parent grid.
// Separate action method for the child grid.
map.Action("ChildGrid", new { OrderID =

© 2014 Syncfusion. All rights reserved. 689 | Page


Essential Grid for ASP.NET MVC Classic

"${OrderID}" });
})

.ToChildGridTemplate());
})
.Render();
}

8. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete, as displayed below.

View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.AllowEdit(true, "Home/ChildOrderSave")// Specify
the action method that will perform the update action.
.AllowNew(true, "Home/ChildAddOrder")// Specify the
action method that will perform the insert action.
.AllowDelete(true, "Home/ChildDeleteOrder");//
Specify the action method that will perform the delete
action.

})
.ToChildGridTemplate());
})
%>

View [cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

© 2014 Syncfusion. All rights reserved. 690 | Page


Essential Grid for ASP.NET MVC Classic

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Caption("Orders")
.Editing( edit=>{
edit.AllowEdit(true, "Home/ChildOrderSave")// Specify
the action method that will perform the update action.
.AllowNew(true, "Home/ChildAddOrder")// Specify the
action method that will perform the insert action.
.AllowDelete(true, "Home/ChildDeleteOrder");//
Specify the action method that will perform the delete action.
})

.ToChildGridTemplate());
})
.Render();
}

9. The Grid control allows users to add new records through grid toolbar items. In this
example, the AddNew, Edit, Delete, Save, and Cancel buttons have been added as
toolbar items in the following code example:
View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting a record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing a record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting a record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for canceling a
request.
})
.ToChildGridTemplate());

© 2014 Syncfusion. All rights reserved. 691 | Page


Essential Grid for ASP.NET MVC Classic

})
%>

View [cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Caption("Orders")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting a record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing a record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting a record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for canceling a
request.
})
.ToChildGridTemplate());
})
.Render();
}
10. Specify the Primary property that uniquely identifies the grid record.

View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

© 2014 Syncfusion. All rights reserved. 692 | Page


Essential Grid for ASP.NET MVC Classic

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add primary key to primary key collections.

}) .ToChildGridTemplate());
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add primary key to primary key collections.

}) .ToChildGridTemplate());
}) .Render();
}

11. Specify the grid editing mode through the EditMode() method.

View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

© 2014 Syncfusion. All rights reserved. 693 | Page


Essential Grid for ASP.NET MVC Classic

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
Specify the edit mode.
})
.ToChildGridTemplate());
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
Specify the edit mode.
})
.ToChildGridTemplate());
}) .Render();
}

12. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records to the database.
Refer to the repository action method displayed below.

Controller

/// <summary>
/// Used to insert the record into the database and refresh the
grid.
/// </summary>
/// <param name="ord">Indicates editable order.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildAddOrder(OrderDetailEdit ord)
{
// Repository action method Add is used to insert records in

© 2014 Syncfusion. All rights reserved. 694 | Page


Essential Grid for ASP.NET MVC Classic

the data source.


OrderDetailRepository.Add(ord);

// After adding the record in the database, refresh the


grid.
var data = OrderDetailRepository.GetAllRecords();
return data.GridActions<OrderDetailEdit>();
}

Note: Refer to repository action codes in Hierarchical Grid > Editing > OrderDetailRepository
Class.

13. In the controller, create a method to save changes, as displayed below. In this example, the
repository method Update() is used to update records to the data source.

Controller

/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Indicates editable order.</param>
/// <returns>HtmlActionResult which returns data displayed on
the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildOrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records in the data source.
OrderDetailRepository.Update(ord);

// After saving the records to the data source, refresh the


grid.
var data = OrderDetailRepository.GetAllRecords();
return data.GridActions<OrderDetailEdit>();
}

14. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() will delete the record from the data
source.

Controller

/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the

© 2014 Syncfusion. All rights reserved. 695 | Page


Essential Grid for ASP.NET MVC Classic

grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildDeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderDetailRepository.Delete(OrderID);

// After deleting refresh the grid.


var data = OrderDetailRepository.GetAllRecords();
return data.GridActions<OrderDetailEdit>();
}

15. Set the data source and render the view.

180.
[Controller]
public ActionResult Index()
{
var data = new
NorthwindDataContext().Orders.Take(200).ToList();
return View(data);

181.
16. In order to work with paging actions, create a post method for the Index action and bind the
data source to the grid as shown in the following code:
182.
183.
[Controller]
/// <summary>
/// Paging action mapper, Paging Request is mapped here
/// </summary>
/// <param name="args">Contains Paging Information.</param>
/// <returns>HtmlActionResult which returns data displayed on
the Grid</returns>
[AcceptVerbs(HttpVerbs.Post)]public ActionResult Index(PagingParams
args)
{
IEnumerable data = new NorthwindDataContext
().Orders.Take(60).ToList();
return data.GridActions<Order>();
}

17. In order to work with the child grid, create a post method for the child grid and bind the data
source to the child grid as shown in the following code:

© 2014 Syncfusion. All rights reserved. 696 | Page


Essential Grid for ASP.NET MVC Classic

[Controller]
[AcceptVerbs(HttpVerbs.Post)]public ActionResult ChildGrid(PagingParams
args, int? OrderID)
{
IEnumerable data = new NorthwindDataContext
().Order_Details.Where(c=>c.OrderID == OrderID).ToList();
return data.GridActions<Order_Detail>();
}

18. Run the application. The grid will appear as shown below:

Figure 237: Hierarchical grid in server mode editing through GridBuilder

4.18.3.2 JSON Mode

4.18.3.2.1 Through GridBuilder

Perform the following steps to create a hierarchical grid through GridBuilder in JSON mode:

1. Create a model in the application (refer to How to > Adding model to the application).
2. Create the Grid control in the view and configure the properties.

© 2014 Syncfusion. All rights reserved. 697 | Page


Essential Grid for ASP.NET MVC Classic

3. Use the ChildGrid method as shown in the following code.


4. The Mappers Action method for the child grid should contain the Foreign Key to relate to
the Parent.
5. It should end with the method ToChildGridTemplate.
View[ASPX]

<%=Html.Syncfusion().Grid<EmployeeView>("GridSrc")
.Caption("Employee Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent grid
as a unique ID for the child grid.
grid.child.ChildGridTemplate(Html.Syncfusion().Grid<OrdersView>("ChildG
rid_${EmployeeID}")
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("JSONChildGrid", new {
EmployeeID = "${ EmployeeID}" });
})
.ToChildGridTemplate());
})
%>

6. For Razor, the code is:

View[cshtml]

@{
Html.Syncfusion().Grid<EmployeeView>("GridSrc")
.Datasource(Model)
.Caption("Employee Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<OrdersView>("ChildGrid_$
{EmployeeID}").
.Mappers(map =>
{
// Specify the foreign key related to the parent
grid.
// Separate action method for the child grid.
map.Action("JSONChildGrid", new {

© 2014 Syncfusion. All rights reserved. 698 | Page


Essential Grid for ASP.NET MVC Classic

EmployeeID = "${ EmployeeID}" });


})
.ToChildGridTemplate());
})
.Render(); }

7. Enable editing by using the Editing method and configure the editing properties such as
AllowNew, AllowEdit, and AllowDelete, as displayed below.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.AllowEdit(true, "Home/ChildAddSave")// Specify the
action method that will perform the update action.
.AllowNew(true, "Home/ChildAddOrder")// Specify the
action method that will perform the insert action.
.AllowDelete(true, "Home/ChildDeleteOrder");//
Specify the action method that will perform the delete
action.

})
.ToChildGridTemplate());
})
%>

View [cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

© 2014 Syncfusion. All rights reserved. 699 | Page


Essential Grid for ASP.NET MVC Classic

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Caption("Orders")
.Editing( edit=>{
edit.AllowEdit(true, "Home/ChildOrderSave")// Specify
the action method that will perform the update action.
.AllowNew(true, "Home/ChildAddOrder")// Specify the
action method which that will perform the insert action.
.AllowDelete(true, "Home/ChildDeleteOrder");//
Specify the action method that will perform the delete action.

})

.ToChildGridTemplate());
})
.Render();
}

8. The Grid control allows users to add new records through grid toolbar items. In this
example, the AddNew, Edit, Delete, Save, and Cancel buttons have been added as
toolbar items in the following code example:
184.
View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting a record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing a record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting a record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for canceling a

© 2014 Syncfusion. All rights reserved. 700 | Page


Essential Grid for ASP.NET MVC Classic

request.
})
.ToChildGridTemplate());
})
%>

185.
186.
View [cshtml]

@{
Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Caption("Orders")
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)// Toolbar
item for inserting a record.
.Add(GridToolBarItems.Edit)// Toolbar
item for editing a record.
.Add(GridToolBarItems.Delete)// Toolbar
item for deleting a record.
.Add(GridToolBarItems.Update)// Toolbar
item for saving changes.
.Add(GridToolBarItems.Cancel);// Toolbar
item for canceling a
request.
})
.ToChildGridTemplate());
})
.Render();
}

9. Specify the Primary property, which uniquely identifies the grid record.

View [ASPX]
<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)

© 2014 Syncfusion. All rights reserved. 701 | Page


Essential Grid for ASP.NET MVC Classic

.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add a primary key to the primary key collections.

}) .ToChildGridTemplate());
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.PrimaryKey(key => key.Add(p =>
p.OrderID)); // Add a primary key to the primary key collections.

}) .ToChildGridTemplate());
}) .Render();
}

10. Specify the grid editing mode through the EditMode() method.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>

© 2014 Syncfusion. All rights reserved. 702 | Page


Essential Grid for ASP.NET MVC Classic

{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal);//
Specify the edit mode.
})
.ToChildGridTemplate());
})
%>

View [cshtml]
@{ Html.Syncfusion().Grid<EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.ActionMode(ActionMode.JSON)
.ChildGrid(child =>
{
// Append the foreign key related to the parent
grid as a unique ID for the child grid.

child.ChildGridTemplate(Html.Syncfusion().Grid<OrderDetailEdit>("ChildG
rid_${OrderID}")
.Caption("OrderDetails Grid")
.Editing( edit=>{
edit.EditMode(GridEditMode.Normal); //
Specify the edit mode.
})
.ToChildGridTemplate());
}) .Render();
}

11. In the controller, create a method to add new records to the grid as displayed below. In this
example, the repository method Add() is being created to insert records into the database.
Refer to the repository action method displayed below.

Controller

/// <summary>
/// Used to insert the record into the database and refresh the
grid.
/// </summary>
/// <param name="ord">Indicates editable order.</param>
/// <returns>HtmlActionResult returns the data displayed on the

© 2014 Syncfusion. All rights reserved. 703 | Page


Essential Grid for ASP.NET MVC Classic

grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildAddOrder(OrderDetailEdit ord)
{
// Repository action method Add is used to insert records in
the data source.
OrderDetailRepository.Add(ord);

// After adding the record in the database, refresh the


grid.
var data = OrderDetailRepository.GetAllRecords();
return data.GridJSONActions<OrderDetailEdit>();
}

Note: Refer to repository action codes in Hierarchical Grid > Editing > OrderDetailRepository
Class.

12. In the controller, create a method to save changes, as displayed below. In this example, the
repository method Update() is used to update records to the data source.

Controller

/// Used to insert the record into the database and refresh the grid.
/// </summary>
/// <param name="ord">Indicates editable order.</param>
/// <returns>HtmlActionResult returns data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildOrderSave(EditableOrder ord)
{
// Repository action method Update is used to update the
records in the data source.
OrderDetailRepository.Update(ord);

// After saving the records to the data source, refresh the


grid.
var data = OrderDetailRepository.GetAllRecords();
return data.GridJSONActions<OrderDetailEdit>();
}

13. In the controller, create a method to delete the records from the database as displayed
below. In this example, the repository action Delete() will delete the record from the data
source.

Controller

© 2014 Syncfusion. All rights reserved. 704 | Page


Essential Grid for ASP.NET MVC Classic

/// <summary>
/// Used for deleting the records from the data source and
refreshing the grid.
/// </summary>
/// <param name="OrderID">Primary key values.</param>
/// <returns>HtmlActionResult returns the data displayed on the
grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ChildDeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary
value record from the data source.
OrderDetailRepository.Delete(OrderID);

// After deleting refresh the grid.


var data = OrderDetailRepository.GetAllRecords();
return data.GridJSONActions<OrderDetailEdit>();
}

14. Set its data source and render the view.

[Controller]
public ActionResult Index()
{
return View();

15. In order to work with paging actions, create a post method for the Index action and bind the
data source to the grid as given in the following code sample:

[Controller]
/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page displays the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
var ordersData = new
NorthwindDataContext().EmployeeViews.ToList();
return ordersData.GridJSONActions<EmployeeView>();
}

16. In order to work with a child grid, create a post method for the child grid and bind the data
source to the child grid as shown in the following code:

© 2014 Syncfusion. All rights reserved. 705 | Page


Essential Grid for ASP.NET MVC Classic

[Controller]

/// <summary>
/// Used to bind the child grid.
/// </summary>
/// <returns>View page displays the grid.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult JSONChildGrid(PagingParams args, string
EmployeeID)
{
IEnumerable data = new
NorthwindDataContext().OrdersViews.Where(c => c.EmployeeID ==
EmployeeID).ToList();
return data.GridJSONActions<OrdersView>();
}

17. Run the application. The grid will appear as shown below:

Figure 238: Hierarchical grid in JSON mode editing through GridBuilder

4.19 Stacked Headers


The stacked headers in Essential Grid for MVC help you see how data in columns can be
categorized and grouped under a single header within the organization of a grid.
Stacked headers allow users to have additional header rows that span across grid columns.
Users can group columns under such headers.

© 2014 Syncfusion. All rights reserved. 706 | Page


Essential Grid for ASP.NET MVC Classic

You can effectively group extensive data with the help of multilevel stacked headers as well.
The skins applied to the grid are applied to the headers as well by default. Essential Grid has 14
built-in skins, and supports customizable themes as well.

Use Case Scenario


Users will be able to clearly see which dimensions of data relate to the same topic, as this feature
helps organize grid data better.
Related columns in the same grid can be grouped under one single heading, so data in those
columns will be seen as part of a whole.
Appearance and Structure
The following figures illustrate the appearance and structure of stacked headers in Essential Grid
for MVC:

Figure 239: Grid with “Product,” “Category,” and “Order Details” as Stacked Headers

© 2014 Syncfusion. All rights reserved. 707 | Page


Essential Grid for ASP.NET MVC Classic

Figure 240: Grid with Multilevel Stacked Headers

Properties

Descript Value it Dependen


Property Type of property
ion accepts cies

Specifies
whether True
the
ShowStackedHeade False
stacked bool NA
r
header is Default value is
enabled or False
not

Specifies
the text to
be
HeaderText string Any string NA
displayed
in the
header

Specifies
the name
Name of the string Any string NA
stacked
header

© 2014 Syncfusion. All rights reserved. 708 | Page


Essential Grid for ASP.NET MVC Classic

Gets or
StackedColumnsColl List<GridStackedColumn
sets the
ection s<T>> GridStackedCol
Stacked NA
umns
columns
collection

Gets or
IList<GridStackedColum
sets the
NestedStackedColu ns<T>> GridStackedCol
nested NA
mns umns
columns
collections

Methods
Method Descrip Parameters Type Return Type
tion
StackedRows() Specifies Name, StackedRows IGridStackedHeaderB
the uilder<>
GridStackedRowBuild
Stacked
er<>
Header
Rows and
it is used
for
creating
stacked
header
rows.

GridStackedCol Specifies Name, StackedColum IGridStackedRowsBui


umns() the ns lder<>
GridStackedColumnB
Stacked
uilder<>
Header
Columns
and it is
used for
creating
stacked
header
columns

© 2014 Syncfusion. All rights reserved. 709 | Page


Essential Grid for ASP.NET MVC Classic

Add() Specifies String or lamda GridStackedCo IGridStackedColumns


columns expression lumns Builder
to be
added to
the
stacked
header

Where do I find the installed samples?


Steps to launch sample:
1. Click Dashboard.
2. Click Run samples to launch the ASP.NET MVC sample browser.
3. Select Rows and Columns>StackedHeader to launch the sample.

4.19.1 Enabling Stacked Headers in Grid MVC


You can enable this feature using either one of the following procedures:

4.19.1.1 Through GridBuilder

The steps to work with the stacked header feature through GridBuilder are as follows:

1. Create a model in the application.


2. Create a strongly typed view.
3. In the view use the Model property in the Datasource() to bind the data source.

View[ASPX]

<%=Html.Syncfusion().Grid<ProductCategory>("ProductGrid").Datasource(Mo
del)
.Caption("Product")
------
.Column(columns =>
{
columns.Add(c => c.ProductID);
columns.Add(c => c.ProductName);
columns.Add(c => c.CategoryID);
columns.Add(c => c.CategoryName);
columns.Add(c => c.Description);
columns.Add(c => c.UnitsInStock);
columns.Add(c => c.UnitPrice);
columns.Add(c => c.QuantityPerUnit);
})

.StackedHeader(sh =>
{

© 2014 Syncfusion. All rights reserved. 710 | Page


Essential Grid for ASP.NET MVC Classic

sh.StackedRows("Row1", sr1 =>


{
sr1.StackedColumn("Products", ac =>
{
ac.Add(c => c.ProductID);
ac.Add(c => c.ProductName);
ac.Add(c => c.CategoryID);
ac.Add(c => c.CategoryName);
ac.Add(c => c.Description);
});
sr1.StackedColumn("Orders", ac =>
{
ac.Add(cc => cc.UnitsInStock);
ac.Add(cc => cc.UnitPrice);
ac.Add(cc => cc.QuantityPerUnit);
});

});
sh.StackedRows("Row2", sr2 =>
{
sr2.StackedColumn("Product Details", cc =>
{
cc.Add(c => c.ProductID);
cc.Add(c => c.ProductName);
});
sr2.StackedColumn("Category Details", c =>
{
c.Add(cc => cc.CategoryID);
c.Add(cc => cc.CategoryName);
c.Add(cc => cc.Description);
});
sr2.StackedColumn("Order Details", c =>
{
c.Add(cc => cc.UnitsInStock);
c.Add(cc => cc.UnitPrice);
c.Add(cc => cc.QuantityPerUnit);
});

});

})
.ShowStackedHeader(true)

%>

View[cshtml]

@{Html.Syncfusion().Grid<ProductCategory>("ProductGrid").Datasource(Mod
el)
.Caption("Product")
-------
.Column(columns =>

© 2014 Syncfusion. All rights reserved. 711 | Page


Essential Grid for ASP.NET MVC Classic

{
columns.Add(c => c.ProductID);
columns.Add(c => c.ProductName);
columns.Add(c => c.CategoryID);
columns.Add(c => c.CategoryName);
columns.Add(c => c.Description);
columns.Add(c => c.UnitsInStock);
columns.Add(c => c.UnitPrice);
columns.Add(c => c.QuantityPerUnit);
})

.StackedHeader(sh =>
{
sh.StackedRows("Row1", sr1 =>
{
sr1.StackedColumn("Products", ac =>
{
ac.Add(c => c.ProductID);
ac.Add(c => c.ProductName);
ac.Add(c => c.CategoryID);
ac.Add(c => c.CategoryName);
ac.Add(c => c.Description);
});
sr1.StackedColumn("Orders", ac =>
{
ac.Add(cc => cc.UnitsInStock);
ac.Add(cc => cc.UnitPrice);
ac.Add(cc => cc.QuantityPerUnit);
});

});
sh.StackedRows("Row2", sr2 =>
{
sr2.StackedColumn("Product Details", cc =>
{
cc.Add(c => c.ProductID);
cc.Add(c => c.ProductName);
});
sr2.StackedColumn("Category Details", c =>
{
c.Add(cc => cc.CategoryID);
c.Add(cc => cc.CategoryName);
c.Add(cc => cc.Description);
});
sr2.StackedColumn("Order Details", c =>
{
c.Add(cc => cc.UnitsInStock);
c.Add(cc => cc.UnitPrice);
c.Add(cc => cc.QuantityPerUnit);
});

});

})
.ShowStackedHeader(true).Render();

© 2014 Syncfusion. All rights reserved. 712 | Page


Essential Grid for ASP.NET MVC Classic

Controller

public ActionResult StackedHeader()


{
var data = new NorthwindDataContext().ProductCategories.ToList();
return View(data);
} PagingParams args
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult StackedHeader(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().ProductCategories.Take(200).ToList();
return data.GridActions<ProductCategory>();
}

4.19.1.2 Through GridPropertiesModel


The steps to work with the stacked header feature through GridPropertiesModel are as follows:
1. Create a model in the application.
2. Create a strongly typed view
3. Add the following code to the view.
View[ASPX]

<%=Html.Syncfusion().Grid<ProductCategory>(
"ProductGrid1", "GridModel",
columns =>
{
columns.Add(c => c.ProductID);
columns.Add(c => c.ProductName);
columns.Add(c => c.CategoryID);
columns.Add(c => c.CategoryName);
columns.Add(c => c.Description);
columns.Add(c => c.UnitsInStock);
columns.Add(c => c.UnitPrice);
columns.Add(c => c.QuantityPerUnit);
}).Render();

%>

View[cshtml]

@{Html.Syncfusion().Grid<ProductCategory>(
"ProductGrid", "GridModel",

© 2014 Syncfusion. All rights reserved. 713 | Page


Essential Grid for ASP.NET MVC Classic

columns =>
{
columns.Add(c => c.ProductID);
columns.Add(c => c.ProductName);
columns.Add(c => c.CategoryID);
columns.Add(c => c.CategoryName);
columns.Add(c => c.Description);
columns.Add(c => c.UnitsInStock);
columns.Add(c => c.UnitPrice);
columns.Add(c => c.QuantityPerUnit);
}).Render();

4. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model.
187.
Controller

GridPropertiesModel<ProductCategory> gridModel = new


GridPropertiesModel<ProductCategory>()
{
DataSource =new
NorthwindDataContext().ProductCategories.ToList(),
Caption = "Product",
-------
ShowStackedHeader = true
};

ViewData["GridModel"] = gridModel;

5. Enable Stacked Header by using the following settings.

Controller

GridStackedRows<ProductCategory> Row1 = new


GridStackedRows<ProductCategory>();
GridStackedColumns<ProductCategory> Columns = new
GridStackedColumns<ProductCategory>();

Row1.HeaderText = "Row1";
Columns = new GridStackedColumns<ProductCategory>();
Columns.HeaderText = "Products";
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "ProductID" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "ProductName" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "CategoryID" });
Columns.NestedStackedColumns.Add(new

© 2014 Syncfusion. All rights reserved. 714 | Page


Essential Grid for ASP.NET MVC Classic

GridStackedColumns<ProductCategory>() { MappingName = "CategoryName"


});
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "Description" });
Row1.StackedColumnsCollection.Add(Columns);

Columns = new GridStackedColumns<ProductCategory>();


Columns.HeaderText = "Orders";
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "UnitsInStock"
});
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "UnitPrice" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "QuantityPerUnit"
});
Row1.StackedColumnsCollection.Add(Columns);

gridModel.GridStackedRows.Add(Row1);

GridStackedRows<ProductCategory> Row2 = new


GridStackedRows<ProductCategory>();

Row2.HeaderText = "Row2";
Columns = new GridStackedColumns<ProductCategory>();
Columns.HeaderText = "Product Details";
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "ProductID" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "ProductName" });
Row2.StackedColumnsCollection.Add(Columns);

Columns = new GridStackedColumns<ProductCategory>();


Columns.HeaderText = "Category Details";
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "CategoryID" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "CategoryName"
});
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "Description" });
Row2.StackedColumnsCollection.Add(Columns);

Columns = new GridStackedColumns<ProductCategory>();


Columns.HeaderText = "Order Details";
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "UnitsInStock"
});
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "UnitPrice" });
Columns.NestedStackedColumns.Add(new
GridStackedColumns<ProductCategory>() { MappingName = "QuantityPerUnit"
});
Row2.StackedColumnsCollection.Add(Columns);

© 2014 Syncfusion. All rights reserved. 715 | Page


Essential Grid for ASP.NET MVC Classic

gridModel.GridStackedRows.Add(Row2);

6. Create a post method for Stacked Header action and bind the data source to grid as like
below code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult StackedHeader(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().ProductCategories.Take(200).ToList();
return data.GridJSONActions<ProductCategory>();
}
}

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Rows and Columns > StackedHeader

4.20 Merge Cells


The merge cells feature allows users to combine two or more adjacent cells into one and display
the content of one cell in the merged cell. Users can also merge the contents of several cells and
display them in one cell.

Use Case Scenarios


The cell merging feature allows neighboring cells with identical values to be combined as one.
This gives users an alternative view of on-screen information.

4.20.1 Tables for Properties, Methods, and Events


GridBuilder Properties
Property Description Type Data Type
AllowMergeCells Enables or disables the bool True/False
cell merging feature.

MergeCellEventArgs Properties
Property Description Type Data Type

© 2014 Syncfusion. All rights reserved. 716 | Page


Essential Grid for ASP.NET MVC Classic

GridCell Gets or sets the ColSpan value for GridTableCell<T> Grid cells
MergeCell.

RangeInfo Gets or sets the RowSpan value for GridCellRangeInfo<T> Grid cell
MergeCell. range info

GridCellRangeInfo Properties
Property Description Type Data Type
RowSpan Gets or sets RowSpan value for int Any Number
MergeCell.

ColSpan Gets or sets ColSpan value for int Any Number


MergeCell.

RowIndex Gets or sets RowIndex. int Any Number

ColumnIndex Gets or sets ColIndex. int Any Number

Methods
Method Description Parameters Type Return Type
SetRange RowSpan and Int args1, int args2 int void
ColSpan values.

Client-Side Events
Event Description Arguments Type
MergeCellInfo Gets or sets MergeCellInfo String IGridBuilder<T>
event handler.

Server Events
Event Description Arguments Type

© 2014 Syncfusion. All rights reserved. 717 | Page


Essential Grid for ASP.NET MVC Classic

MergeCellInfo Used to merge cells. Action<GridPropertiesModel<T>, IGridBuilder<T>


MergeCellEventArgs<T>>

4.20.2 Adding Merge Cells to an Application


Server Mode
4.20.2.1.1 Through GridBuilder
1. Create a model in the application (Refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).

3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [cshtml]

@(Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableRowHover(false)
.ActionMode(ActionMode.Server)
.AutoFormat(Skins.Marble)
.Column(column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
.AllowMergeCells(true)
.MergeCellInfo((sender,args) =>
Html.RenderAction("QueryAction", "GridCellMerging", new { sender = this,
args = args }))

View [ASPX]

<%=Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid")

© 2014 Syncfusion. All rights reserved. 718 | Page


Essential Grid for ASP.NET MVC Classic

.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.EnableRowHover(false)
.ActionMode(ActionMode.Server)
.AutoFormat(Skins.Marble)
.Column(column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
.AllowMergeCells(true)
.MergeCellInfo((sender,args) =>
Html.RenderAction("QueryAction", "GridCellMerging", new { sender = this,
args = args }))

%>

4. Set its data source and render the view.

[Controller – C#]

//
// GET: /GridCellMerging/
public ActionResult Index ()
{
var data = new NorthwindDataContext().OrderDetailsViews;
return View(data);
}

[Controller - VB]

'
' GET: /GridCellMerging/
Public Function Index() As ActionResult
Dim data = New NorthwindDataContext ().OrderDetailsViews
Return View(data)
End Function

© 2014 Syncfusion. All rights reserved. 719 | Page


Essential Grid for ASP.NET MVC Classic

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.

[Controller – C#]

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ServerCellMerging(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().OrderDetailsViews;
ActionResult result = data.GridActions<OrderDetailsView>();
var engineSource = result as
GridHtmlActionResult<OrderDetailsView>;
engineSource.GridModel.MergeCellInfo = QueryAction;
return engineSource;
}

public void QueryAction(GridPropertiesModel<OrderDetailsView>


sender, MergeCellEventArgs<OrderDetailsView> args)
{
if (args.GridCell.TableCellType ==
GridTableCellType.RecordFieldCell)
{
if (args.GridCell.Column.MappingName == "OrderID" &&
args.RangeInfo.RowIndex == 1)
{
if (args.GridCell.Text.ToString() == "10248")
args.RangeInfo.SetRange(3, 1);
}
else if (args.GridCell.Column.MappingName == "OrderID" &&
args.RangeInfo.RowIndex == 4)
{
if (args.GridCell.Text.ToString() == "10249")
args.RangeInfo.SetRange(2, 1);
}
else if (args.GridCell.Column.MappingName == "OrderID" &&
args.RangeInfo.RowIndex == 6)
{
if (args.GridCell.Text.ToString() == "10250")
args.RangeInfo.SetRange(3, 1);
}
else if (args.GridCell.Column.MappingName == "OrderID" &&
args.RangeInfo.RowIndex == 9)
{
if (args.GridCell.Text.ToString() == "10251")
args.RangeInfo.SetRange(3, 1);
}
if (args.GridCell.Column.MappingName == "ProductName" &&
args.RangeInfo.RowIndex == 3)
{
if (args.GridCell.Text.ToString() == "Mozzarella di
Giovanni")
args.RangeInfo.SetRange(2, 1);
}
else if (args.GridCell.Column.MappingName == "Quantity" &&
args.RangeInfo.RowIndex == 3)

© 2014 Syncfusion. All rights reserved. 720 | Page


Essential Grid for ASP.NET MVC Classic

{
if (args.GridCell.Text.ToString() == "5")
args.RangeInfo.SetRange(2, 1);
}
else if (args.GridCell.Column.MappingName == "UnitPrice" &&
args.RangeInfo.RowIndex == 3)
{
if (args.GridCell.Text.ToString() == "$34.80")
args.RangeInfo.SetRange(2, 1);
}
else if (args.GridCell.Column.MappingName ==
"ExtendedPrice" && args.RangeInfo.RowIndex == 3)
{
if (args.GridCell.Text.ToString() == "174.0000")
args.RangeInfo.SetRange(2, 1);
}
}
}

[Controller – VB]

<AcceptVerbs(HttpVerbs.Post)> _
Public Function ServerCellMerging(ByVal args As PagingParams) As
ActionResult
Dim data As IEnumerable = New
NorthwindDataContext().OrderDetailsViews
Dim result As ActionResult = data.GridActions(Of
OrderDetailsView)()
Dim engineSource = TryCast(result, GridHtmlActionResult(Of
OrderDetailsView))
engineSource.GridModel.MergeCellInfo = QueryAction
Return engineSource
End Function
Public Sub QueryAction(ByVal sender As GridPropertiesModel(Of
OrderDetailsView), ByVal args As MergeCellEventArgs(Of OrderDetailsView))
If args.GridCell.TableCellType =
GridTableCellType.RecordFieldCell Then
If args.GridCell.Column.MappingName = "OrderID" AndAlso
args.RangeInfo.RowIndex = 1 Then
If args.GridCell.Text.ToString() = "10248" Then
args.RangeInfo.SetRange(3, 1)
End If
ElseIf args.GridCell.Column.MappingName = "OrderID" AndAlso
args.RangeInfo.RowIndex = 4 Then
If args.GridCell.Text.ToString() = "10249" Then
args.RangeInfo.SetRange(2, 1)
End If
ElseIf args.GridCell.Column.MappingName = "OrderID" AndAlso
args.RangeInfo.RowIndex = 6 Then
If args.GridCell.Text.ToString() = "10250" Then
args.RangeInfo.SetRange(3, 1)
End If

© 2014 Syncfusion. All rights reserved. 721 | Page


Essential Grid for ASP.NET MVC Classic

ElseIf args.GridCell.Column.MappingName = "OrderID" AndAlso


args.RangeInfo.RowIndex = 9 Then
If args.GridCell.Text.ToString() = "10251" Then
args.RangeInfo.SetRange(3, 1)
End If
End If
If args.GridCell.Column.MappingName = "ProductName" AndAlso
args.RangeInfo.RowIndex = 3 Then
If args.GridCell.Text.ToString() = "Mozzarella di
Giovanni" Then
args.RangeInfo.SetRange(2, 1)
End If
ElseIf args.GridCell.Column.MappingName = "Quantity"
AndAlso args.RangeInfo.RowIndex = 3 Then
If args.GridCell.Text.ToString() = "5" Then
args.RangeInfo.SetRange(2, 1)
End If
ElseIf args.GridCell.Column.MappingName = "UnitPrice"
AndAlso args.RangeInfo.RowIndex = 3 Then
If args.GridCell.Text.ToString() = "$34.80" Then
args.RangeInfo.SetRange(2, 1)
End If
ElseIf args.GridCell.Column.MappingName = "ExtendedPrice"
AndAlso args.RangeInfo.RowIndex = 3 Then
If args.GridCell.Text.ToString() = "174.0000" Then
args.RangeInfo.SetRange(2, 1)
End If
End If
End If
End Sub

6. Run the application. The grid will appear as shown below.

Figure 241: Grid with Merged Cells in Server Mode

© 2014 Syncfusion. All rights reserved. 722 | Page


Essential Grid for ASP.NET MVC Classic

4.20.2.1.2 Through GridPropertiesModel

1. Create a model in the application (Refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [cshtml]

@(Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid",
"GridModel", column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
}))

View [ASPX]

<%= Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid",
"GridModel", column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})

© 2014 Syncfusion. All rights reserved. 723 | Page


Essential Grid for ASP.NET MVC Classic

%>

4. Create a GridPropertiesModel in the Index method. Bind the data source using the
DataSource property and pass the model from controller to view using the ViewData class
as demonstrated in the following code.

[Controller]

//
// GET: /ServerModel/

public ActionResult Index ()


{
GridPropertiesModel<OrderDetailsView> model = new
GridPropertiesModel<OrderDetailsView>()
{
DataSource = new
NorthwindDataContext().OrderDetailsViews.Take(10),
ActionMode = ActionMode.Server,
AllowMergeCells = true,
MergeCellInfo=OnQueryCellInfo
};
ViewData["GridModel"] = model;
return View();
}

public void OnQueryCellInfo(GridPropertiesModel<OrderDetailsView> sender,


MergeCellEventArgs<OrderDetailsView> args)
{
if (args.GridCell.TableCellType ==
GridTableCellType.RecordFieldCell)
{
if (args.GridCell.Column.MappingName == "OrderID" &&
args.RangeInfo.RowIndex == 4)
{
if (args.GridCell.Text.ToString() == "10249")
args.RangeInfo.SetRange(2, 1);
}
if (args.GridCell.Column.MappingName == "ProductName" &&
args.RangeInfo.RowIndex == 3)
{
if (args.GridCell.Text.ToString() == "Mozzarella di
Giovanni")
args.RangeInfo.SetRange(2, 1);
}
}
}

5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.

© 2014 Syncfusion. All rights reserved. 724 | Page


Essential Grid for ASP.NET MVC Classic

[Controller – C#]

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().OrderDetailsViews;
return data.GridActions <OrderDetailsView>();
}

[Controller – VB]

<AcceptVerbs(HttpVerbs.Post)> _
Public Function Index(ByVal args As PagingParams) As ActionResult
Dim data As IEnumerable = New NorthwindDataContext
().OrderDetailsViews
Return data.GridActions (Of OrderDetailsView)()
End Function

6. Run the application. The grid will appear as shown in the following figure.

Figure 242: Grid with Merged Cells in Server Mode

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Cell Merging > Server Merging

4.20.2.2 JSON Mode

© 2014 Syncfusion. All rights reserved. 725 | Page


Essential Grid for ASP.NET MVC Classic

4.20.2.2.1 Through GridBuilder


1. Create a model in the application (refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.

View [cshtml]

@(Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid")

.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.ActionMode(ActionMode.JSON)
.AutoFormat(Skins.Marble)
.AllowMergeCells(true)
.Column(column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})
.ClientSideEvents(ce =>
{
ce.MergeCellInfo("MergeCellInfo");
}))

<script type="text/javascript">
function MergeCellInfo(sender, args) {
if (args.GridCell.Column.Member == "OrderID") {
if (args.GridCell.Text.toString() == "10248" && args.RowIndex
== 1)
args.SetRange(3, 1);
else if (args.GridCell.Text.toString() == "10249" &&
args.RowIndex == 4)
args.SetRange(2, 1);
else if (args.GridCell.Text.toString() == "10250" &&
args.RowIndex == 6)
args.SetRange(3, 1);
else if (args.GridCell.Text.toString() == "10251" &&
args.RowIndex == 9)
args.SetRange(3, 1);

© 2014 Syncfusion. All rights reserved. 726 | Page


Essential Grid for ASP.NET MVC Classic

}
if (args.GridCell.Column.Member == "ProductName" && args.RowIndex
== 3) {
if (args.GridCell.Text.toString() == "Mozzarella di Giovanni")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "Quantity" && args.RowIndex
== 3) {
if (args.GridCell.Text.toString() == "5")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "UnitPrice" &&
args.RowIndex == 3) {
if (args.GridCell.Text.toString() == "$34.80")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "ExtendedPrice" &&
args.RowIndex == 3) {
if (args.GridCell.Text.toString() == "174")
args.SetRange(2, 1);
}
}
</script>

View [ASPX]

<%=Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid")
.Datasource(Model)
.Caption("Orders")
.EnablePaging()
.ActionMode(ActionMode.JSON)
.AutoFormat(Skins.Marble)
.AllowMergeCells(true)
.Column(column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})

© 2014 Syncfusion. All rights reserved. 727 | Page


Essential Grid for ASP.NET MVC Classic

.ClientSideEvents(ce =>
{
ce.MergeCellInfo("MergeCellInfo");
})
%>

<script type="text/javascript">
function MergeCellInfo(sender, args) {
if (args.GridCell.Column.Member == "OrderID") {
if (args.GridCell.Text.toString() == "10248" && args.RowIndex
== 1)
args.SetRange(3, 1);
else if (args.GridCell.Text.toString() == "10249" &&
args.RowIndex == 4)
args.SetRange(2, 1);
else if (args.GridCell.Text.toString() == "10250" &&
args.RowIndex == 6)
args.SetRange(3, 1);
else if (args.GridCell.Text.toString() == "10251" &&
args.RowIndex == 9)
args.SetRange(3, 1);

}
if (args.GridCell.Column.Member == "ProductName" && args.RowIndex
== 3) {
if (args.GridCell.Text.toString() == "Mozzarella di Giovanni")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "Quantity" && args.RowIndex
== 3) {
if (args.GridCell.Text.toString() == "5")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "UnitPrice" &&
args.RowIndex == 3) {
if (args.GridCell.Text.toString() == "$34.80")
args.SetRange(2, 1);
}
else if (args.GridCell.Column.Member == "ExtendedPrice" &&
args.RowIndex == 3) {
if (args.GridCell.Text.toString() == "174")
args.SetRange(2, 1);
}
}
</script>
188.
4. Set its data source and render the view.
189.
[Controller – C#]

//
// GET: / JsonCellMerging /
public ActionResult Index ()
{
var data = new NorthwindDataContext().OrderDetailsViews;
return View(data);

© 2014 Syncfusion. All rights reserved. 728 | Page


Essential Grid for ASP.NET MVC Classic

[Controller - VB]

'
' GET: / JsonCellMerging /
Public Function Index() As ActionResult
Dim data = New NorthwindDataContext ().OrderDetailsViews
Return View(data)

End Function
190.
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
191.
[Controller – C#]

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().OrderDetailsViews;
return data.GridJSONActions <OrderDetailsView>();
}

[Controller – VB]

<AcceptVerbs(HttpVerbs.Post)> _
Public Function Index(ByVal args As PagingParams) As ActionResult
Dim data As IEnumerable = New NorthwindDataContext
().OrderDetailsViews
Return data.GridJSONActions (Of OrderDetailsView)()
End Function
192.
6. Run the application. The grid will appear as shown in the following figure.

© 2014 Syncfusion. All rights reserved. 729 | Page


Essential Grid for ASP.NET MVC Classic

Figure 243: Grid with Merged Cells

4.20.2.2.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
View [cshtml]

@(Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid",
"GridModel", column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
}))

View [ASPX]

<%= Html.Syncfusion().Grid<OrderDetailsView>("OrderDetails_grid",
"GridModel", column =>
{
column.Add(p =>
p.OrderID).Width(110).TextAlign(TextAlignment.Right).HeaderText("Order
ID");
column.Add(p =>
p.ProductID).Width(100).TextAlign(TextAlignment.Right).HeaderText("Product
ID");
column.Add(p => p.ProductName).HeaderText("Product
Name");
column.Add(P =>
P.Quantity).Width(100).TextAlign(TextAlignment.Right);
column.Add(p =>
p.UnitPrice).Width(100).TextAlign(TextAlignment.Right).Format("{0:C}").Head
erText("Unit Price");
column.Add(p =>
p.ExtendedPrice).HeaderText("Extended Price").Width(110);
})

%>

© 2014 Syncfusion. All rights reserved. 730 | Page


Essential Grid for ASP.NET MVC Classic

4. Create a GridPropertiesModel in the Index method. Bind the data source using the
DataSource property and pass the model from controller to view using the ViewData class
as shown in the following sample.

193.
[Controller – C#]

//
// GET: /JsonModel/

public ActionResult Index ()


{
GridPropertiesModel<OrderDetailsView> model = new
GridPropertiesModel<OrderDetailsView>()
{
DataSource = new
NorthwindDataContext().OrderDetailsViews.Take(10),
ActionMode = ActionMode.JSON,
AllowMergeCells = true,
ClientSideEvents =
{
MergeCellInfo = "MergeCellInfo"
}

};
ViewData["GridModel"] = model;
return View(ViewData["GridModel"]);
}

[Controller – VB]

'
' GET: /JsonModel/

Public Function Index() As ActionResult

Dim model As New GridPropertiesModel(Of OrderDetailsView)() With


{ _
.DataSource = New
NorthwindDataContext().OrderDetailsViews.Take(10), _
.ActionMode = ActionMode.JSON, _
.AllowMergeCells = True, _
.ClientSideEvents = {MergeCellInfo := "MergeCellInfo"} _
}
ViewData("GridModel") = model
Return View(ViewData("GridModel"))
End Function
194.
5. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code.
195.
[Controller – C#]

© 2014 Syncfusion. All rights reserved. 731 | Page


Essential Grid for ASP.NET MVC Classic

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().OrderDetailsViews;
return data.GridJSONActions <OrderDetailsView>();
}

[Controller – VB]

<AcceptVerbs(HttpVerbs.Post)> _
Public Function Index(ByVal args As PagingParams) As ActionResult
Dim data As IEnumerable = New NorthwindDataContext
().OrderDetailsViews
Return data.GridJSONActions (Of OrderDetailsView)()
End Function
196.
6. Run the application. The grid will appear as shown below.
197.

Figure 244: Grid with Merged Cells in JSON Mode

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Cell Merging > JSON Merging

4.21 Freezing Rows and Columns


When scrolling the grid content, some columns and rows should be locked, similar to freeze
panes in Microsoft Excel. This is quite useful when you want to make a part of the data (in
columns/rows) visible to end users at all times.

© 2014 Syncfusion. All rights reserved. 732 | Page


Essential Grid for ASP.NET MVC Classic

Use Case Scenarios


Users can freeze rows and columns to the left or top of the grid so that they are always visible
when scrolling through a grid with a large number of rows or columns.

4.21.1.1 Freezing Grid Rows/Columns in an Application

4.21.1.1.1 Through GridBuilder

To freeze the rows and columns in the grid using GridBuilder:


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure the properties.
4. Set the number of rows that need to be frozen using the FrozenRows method.
5. Set the number of columns that need to be frozen using FrozenColumns method.
6. Scrolling can be enabled using EnableScrolling method. The Grid width should be less
than the total columns width.

View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins. Marble)
.FrozenRows(2)
.FrozenColumns(1)
.EnableScrolling()
.Scrolling(scroll => scroll.Height(150).Width(535))
.Column( columns => {
columns.Add(p => p.OrderID).Width(200);
columns.Add(p => p.CustomerID).Width(200);
columns.Add(p => p.EmployeeID).Width(200);
columns.Add(P => P.ShipCountry).Width(200);
columns.Add(p => p.OrderDate).Width(200).Format("{0:dd-MM-
yyyy}");
})
%>

© 2014 Syncfusion. All rights reserved. 733 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Marble)
.FrozenRows(2)
.FrozenColumns(1)
.EnableScrolling()
.Scrolling(scroll => scroll.Height(150).Width(535))
.Column( columns => {
columns.Add(p => p.OrderID).Width(200);
columns.Add(p => p.CustomerID).Width(200);
columns.Add(p => p.EmployeeID).Width(200);
columns.Add(P => P.ShipCountry).Width(200);
columns.Add(p => p.OrderDate).Width(200).Format("{0:dd-MM-
yyyy}");
}).Render();
}

7. Set its data source and render the view.

[Controller]
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders;
return View(data);
}

8. Run the application. The grid will appear as displayed in the following screenshot:

© 2014 Syncfusion. All rights reserved. 734 | Page


Essential Grid for ASP.NET MVC Classic

Figure 245: “OrderID” Column and First Two Rows Frozen

© 2014 Syncfusion. All rights reserved. 735 | Page


Essential Grid for ASP.NET MVC Classic

Figure 246: “OrderID” Column and First Two Rows Visible after Scrolling

4.21.1.1.2 Through GridPropertiesModel


To freeze the rows and columns in the grid using GridPropertiesModel:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view.
198.
View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1","GridModel", column
s => {
columns.Add(p => p.OrderID).Width(200);
columns.Add(p => p.CustomerID).Width(200);
columns.Add(p => p.EmployeeID).Width(200);
columns.Add(P => P.ShipCountry).Width(200);
columns.Add(p => p.OrderDate).Width(200).Format("{0:dd-MM-
yyyy}");
})%>

199.
View [cshtml]
@{
Html.Syncfusion().Grid<Order>("Grid1","GridModel", columns => {
columns.Add(p => p.OrderID).Width(200);
columns.Add(p => p.CustomerID).Width(200);
columns.Add(p => p.EmployeeID).Width(200);
columns.Add(P => P.ShipCountry).Width(200);
columns.Add(p => p.OrderDate).Width(200).Format("{0:dd-MM-
yyyy}");
}).Render();
}

4. Create a GridPropertiesModel in the Index method. Use the Localize property to specify
the culture details.

[Controller]

public ActionResult Index()


{
GridPropertiesModel<Order> gridModel = new
GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption = "Orders",
AutoFormat = Syncfusion.Mvc.Shared.Skins.Marble,
FrozenRows = 2,

© 2014 Syncfusion. All rights reserved. 736 | Page


Essential Grid for ASP.NET MVC Classic

FrozenColumns = 1,
Width = 635,
Height = 150,
AllowScrolling = true
};

ViewData["GridModel"] = gridModel;
return View();
}

5. Run the application, the grid will appear as shown in the following screenshot:

Figure 247: “OrderID” Column and First Two Rows Frozen

© 2014 Syncfusion. All rights reserved. 737 | Page


Essential Grid for ASP.NET MVC Classic

Figure 248: “OrderID” Column and First Two Rows Visible after Scrolling

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Rows and Columns > Frozen rows and columns

Tables for Properties, Methods, and Events


Properties

Property Description Type Data Type


FrozenRows Gets or sets the Server side Integer
number of rows that
need to be frozen.
Scrolling should be
enabled.

FrozenColumns Gets or sets the Server side Integer


number of columns
that need to be
frozen. Scrolling
should be enabled

© 2014 Syncfusion. All rights reserved. 738 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type Data Type


and grid width should
be less than the total
columns width.

EnableScrolling Indicates whether Server Side Boolean


scrolling is enabled or
not.

Methods

Method Description Parameters Type Return


Type
FrozenRows Gets the number (int frozenRows) Server-side Void
of rows that
need to be
frozen. Scrolling
should be
enabled.

FrozenColumns Gets or sets the (int frozenColumns) Server-side Void


number of
columns that
need to be
frozen. Scrolling
should be
enabled and grid
width should be
less than the
total columns
width.

EnableScrolling Indicates No Arguments Server-side Void


whether scrolling
is enabled or
not.

set_frozenRows Gets the number (int frozenRows) Client-side Void


of rows that
need to be
frozen. Scrolling
should be
enabled.

© 2014 Syncfusion. All rights reserved. 739 | Page


Essential Grid for ASP.NET MVC Classic

set_frozenColumns
Gets or sets the (int frozenColumns) Client-side Void
number of
columns that
need to be
frozen. Scrolling
should be
enabled and grid
width should be
less than the
total columns
width.
freezePanes
Keep the rows No Argumnets Client-side Boolean
and columns
visible while Grid
scrolls based on
the current
selection.
unFreezePanes
Unlock all rows No Arguments Client-side Void
and columns to
scroll through
the entire grid.

4.21.1.2 Freezing Panes


Use the following code sample in the client side to freeze panes based on the current selection.

[JavaScript]

var grid = $find("MyGrid");

grid.freezePanes();

If the third row and second column of the grid is selected, freeze panes will keep the first two
rows and first column visible as always while the grid is scrolling.

© 2014 Syncfusion. All rights reserved. 740 | Page


Essential Grid for ASP.NET MVC Classic

Figure 249: Rows and Columns are Frozen Based on Selection

4.21.1.3 Unfreezing Panes


Use the following code sample in client side to unfreeze the panes based on the current
selection.

[JavaScript]

var grid = $find("MyGrid");


grid.unFreezePanes();

Unlock all the rows and columns to scroll through the entire grid.

© 2014 Syncfusion. All rights reserved. 741 | Page


Essential Grid for ASP.NET MVC Classic

Figure 250: Before Calling unFreezePanes

Figure 251: After Calling unFreezePanes


Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Rows and Columns > Freeze Panes

© 2014 Syncfusion. All rights reserved. 742 | Page


Essential Grid for ASP.NET MVC Classic

4.21.1.4 Appearance

The following screenshot displays a dark border, indicating columns and rows that are frozen.

Figure 252: Border Shows Frozen Rows and Columns

4.22 Auto Wrap-Up of Column Cells


This feature helps you view content more easily than conventional methods in a grid. This is
because content that exceeds the space in a particular cell can be resized to fit in the cell and
can be carried over to the next line.
You can resize the content in cells using the following settings:
 ClipContent: This property depends on the AllowAutoWrap property—it is only enabled
when AllowAutoWrap is enabled. When you choose to clip content, you will not be able
to resize the column width beyond the minimum limit (this is because the
AllowAutoWrap property is enabled. However, if this property is disabled, ClipContent
will also be disabled)
 ResizeToFit: This property allows you to choose if you want the column width
accommodate the content automatically.

Use Case Scenario


This helps the user to see the content in one cell without having to scroll sideways to view the
entire content. This allows easy viewing since content is carried to the next line.

Appearance and Structure

© 2014 Syncfusion. All rights reserved. 743 | Page


Essential Grid for ASP.NET MVC Classic

The following figures illustrate the appearance and structure of the auto wrap feature and its
settings:

Figure 253: Grid with AutoWrap Enabled in the Highlighted Column

Figure 254: Grid with ClipContent and ResizeToFit Enabled

Notes:
 ClipContent is only enabled when AutoWrap is enabled.
 ResizeToFit doesn’t depend on the AutoWrap property.

4.22.1 Properties

© 2014 Syncfusion. All rights reserved. 744 | Page


Essential Grid for ASP.NET MVC Classic

Type of Value it
Property Description Dependencies
Property Accepts

This property allows


you to choose if you
would want to resize
the content in a True
AllowResizing particular cell or not. bool NA
If not, this feature’s False
properties and its
other settings will be
disabled.

Depends on the
Specifies whether the
AllowResizing
autowrap is enabled
property.

True If AllowResizing is
AllowAutoWrap Content will wrap to bool
False true, then you have
the next line if the
the option of
content exceeds the
enabling the
boundary of the
AllowAutoWrap
Column Cells
property.

Specifies if content is Depends on the


resizable or not. AllowResizing
property.
If it is resizable, the
ResizeToFit If AllowResizing is
ResizeSettings ResizeToFit sub- enum
property is enabled. ClipContent true, then you have
the option of
If it is not resizable, enabling the
the ClipContent sub- AllowAutoWrap
property is enabled. property.

Sets whether the


resize to fit content is Depends on the
enabled ResizeSettings—
True
ResizeToFit bool
False ResizeToFit is a
Double-clicking the sub-property of
resize handle will have ResizeSettings
the column
automatically resized

© 2014 Syncfusion. All rights reserved. 745 | Page


Essential Grid for ASP.NET MVC Classic

to fit the widest cell


content without
wrapping

Depends on the
Specifies whether the ResizeSettings—
cell content will be True
ClipContent bool
clipped on column False ClipContent is a
resizing sub-property of
ResizeSettings

Events
Event Description Arguments Type Reference links

This event occurs when String handler


OnResizingSt Client-Side NA
the column is start to
art
resize

This event occurs when String handler


OnResizingEn Client-Side NA
the column resizing is
d
going to be end

This event occurs after String handler


Resized Client-Side NA
the column is resized

Using Client-Side Events

Using the OnRecordCollapsing event, users can avoid a collapse event. Using the
OnRecordExpanding event, users can avoid an expand event.

The client-side events are used in ASPX as shown below in server mode through GridBuilder:
View[ASPX]

<%=Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
.AllowResizing(true)
.ClientSideEvents(eve =>

© 2014 Syncfusion. All rights reserved. 746 | Page


Essential Grid for ASP.NET MVC Classic

{
eve. OnResizingStart ("OnResizingStart ");
eve. OnResizingEnd ("OnResizingEnd ");
eve. Resized ("Resized ");
})

%>

For Razor, use the code shown below in server mode through GridBuilder.
View[cshtml]
@{
Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.AutoFormat(Skins.Almond)
. AllowResizing(true)
.ClientSideEvents(eve =>
{
eve. OnResizingStart ("OnResizingStart ");
eve. OnResizingEnd ("OnResizingEnd ");
eve. Resized ("Resized ");
})
.Render();
}

4.22.2 Enabling Auto Wrap-Up in Grid MVC


You can enable this feature using either one of the following procedures:

4.22.2.1 Through GridBuilder

The steps to work with the auto wrap feature through GridBuilder are as follows:

1. Create a model in the application.


2. Create a strongly typed view.
3. In the view, use the Model property in the Datasource() to bind the data source.

View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
--------
--------

© 2014 Syncfusion. All rights reserved. 747 | Page


Essential Grid for ASP.NET MVC Classic

.AutoFormat(Skins.Sandune)
.AllowResizing(true)
.AllowAutoWrap(true)
.ResizeSettings(resize => {
resize.ResizeToFit(true);
resize.ClipContent(true);
})
%>

View[cshmtl]

@{Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
--------
--------
.AutoFormat(Skins.Sandune)
.AllowResizing(true)
.AllowAutoWrap(true)
.ResizeSettings(resize => {
resize.ResizeToFit(true);
resize.ClipContent(true);
}).Render();
}

Controller

public ActionResult AutoWrap()


{
return View(OrderRepository.GetAllRecords());
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AutoWrap(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200).ToList();
return data.GridActions<Order>();
}

© 2014 Syncfusion. All rights reserved. 748 | Page


Essential Grid for ASP.NET MVC Classic

4.22.2.2 Through GridPropertiesModel


The steps to work with the auto wrap feature through GridPropertiesModel are as follows:
1. Create a model in the application.
2. Create a strongly typed view.
3. Add the following code to the view.
View[ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>(
"Grid1", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date");
column.Add(p => p.Freight).HeaderText("Freight");
})

%>

View[cshtml]

@{Html.Syncfusion().Grid<EditableOrder>(
"Grid1", "GridModel",
column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer
ID");
column.Add(p => p.ShipCountry).HeaderText("Ship
Country");
column.Add(p => p.OrderDate).HeaderText("Order
Date");
column.Add(p => p.Freight).HeaderText("Freight");
})

%>

4. Create a GridPropertiesModel and assign the grid properties in the model.

© 2014 Syncfusion. All rights reserved. 749 | Page


Essential Grid for ASP.NET MVC Classic

Controller

GridPropertiesModel<EditableOrder> gridModel = new


GridPropertiesModel<EditableOrder>()
{
DataSource = OrderRepository.GetAllRecords(),
--------
AllowResizing = true,
AllowAutoWrap = true,
Height = 225,
AutoFormat = Skins.Sandune,
};

GridResizing resize = new GridResizing()


{
ResizeToFit = true,
ClipContent = true,
};

gridModel.ResizeSettings = resize;

200.
5. Create a Post method for AutoWrap actions and bind the data source to the grid as given
in the following code:
201.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AutoWrap(PagingParams args, int? OrderID,
GridEditMode? GridMode)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}

6. Run the application and resize columns as desired.

Sample Link
To view the samples, follow the steps below:
1. Open the Grid sample browser from the dashboard (Refer to the Samples and Location
chapter).
2. Navigate to Grid.MVC > Rows and Columns > AutoWrap Column Cells

© 2014 Syncfusion. All rights reserved. 750 | Page


Essential Grid for ASP.NET MVC Classic

4.23 Client-Side Events and Methods


Methods

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
set_currentCellBackground Used to apply CSS string NA
class to the Current
cell.

set_selectedAreaBackgroundC Used to apply CSS string NA


olorCss class to the selected
area which can be
grid, cell or row.

set_rowHeaderSelectionCss Used to apply CSS string NA


class to the selected
row header.

set_columnHeaderSelectionCss Used to apply CSS string NA


class to the selected
column header

set_CloneCss Used to apply CSS string NA


class to the dragging
element

set_enterKey() Used to set the Enter string Up


key direction in grid.
Down,
Left,

Right

set_tabKey Used to set the Tab string Up


key direction in grid.
Down,

Left,
Right

set_PrimaryKeys Get or set the primary object NA


key values.

© 2014 Syncfusion. All rights reserved. 751 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
set_dropColumn(startIndex,endI Get or set the int NA
ndex) startindex and
endindex value for
the drag and drop
column

set_ShowRowHeader Show/Hide the Boolean NA


rowheader in grid

set_EnableRowHover Enable or disable the Boolean NA


rowhover property in
grid

set_AllowEditing Enable or disable the Boolean NA


edit action in the
editing mode.

set_AllowGrouping Enable or disable the Boolean NA


grouping action in the
grid.

set_AllowPaging Enable or disable the Boolean NA


paging action in the
grid.

set_AllowSelection Enable or disable the Boolean NA


row selection action
in the grid.

set_CurrentPage Used to set the int NA


current page of the
grid.

set_PageSize Used to set the Page int NA


size of the grid

set_selectCell(rowIndex,Colum Used to select the int NA


nIndex) cell in client side

set_ShowGroupDropArea Enable or disable the Boolean NA


group drop area of
the grid.

© 2014 Syncfusion. All rights reserved. 752 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
selectRow(Index) Index void It highlights NA
the
corresponding
row of the
Row Index
value given in
the code.

deselectRow(Index) Index void It deselects NA


the row
selected using
the
selectRow()
method.

selectMutipleRows(startRowInd startRowIndex, void It highlights NA


ex,endRowIndex) the multiple
endRowIndex
rows from
start to end of
the Row Index
value given in
code.

showRow(Index) index void It displays the NA


corresponding
row whose
Row index is
mentioned in
the code.

hideRow(index) Index void It hides the NA


corresponding
row whose
Row Index is
mentioned in
the code.

showColumn(ColumnName) Column name as void It displays the NA


string. corresponding
column whose
column name
is mentioned

© 2014 Syncfusion. All rights reserved. 753 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
in the code.

hideColumn(ColumnName) Column name as void It hides the NA


string. corresponding
column whose
column name
is mentioned
in the code.

showColumnByIndex ColumnIndex void It shows the NA


corresponding
column whose
column index
is mentioned
in the code.

hideColumnByIndex ColumnIndex void It hides the NA


corresponding
column whose
column index
is mentioned
in the code.

DoSorting(ColumName,Sorting Column Name, Sort void Sorting a NA


Direction) Direction particular
column
through the
Client side.

clearSortingforColumn(Column Column Name void Clear sorting


Name) for a particular
NA
column
through the
Client side.

GroupBy(ColumnName) Column Name void Grouping a NA


particular
column
through the
client side.

UnGroupBy(ColumnName) Column Name void Ungrouping a NA

© 2014 Syncfusion. All rights reserved. 754 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
particular
column
through the
client side.

collapseAll() void Collapse the NA


grouped
column.

expandAll() void Expand the NA


grouped
column.

sendSearchingRequest void Send NA


searching
request in the
client side.

sendFilteringRequest void Send filtering NA


request in the
client side.

sendGroupingRequest void Send grouping NA


request in the
client side.

sendPagingRequest void Send paging NA


request in the
client side.

sendSortingRequest void Send sorting NA


request in the
client side.

sendRefreshRequest void Send refresh NA


request in the
client side.

sendHtmlActionRequest void Send HTML NA


action request
in the client
side.

© 2014 Syncfusion. All rights reserved. 755 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
sendExcelExportRequest void Send Excel NA
export request
in the client
side.

sendWordExportRequest void Send Word NA


export request
in the client
side.

sendPDFExportRequest void Send PDF NA


export request
in the client
side.

sendAddNewRequest void Send add new NA


request in the
client side.

sendEditingRequest void Send editing NA


request in the
client side.

sendSaveRequest void Send save NA


request in the
client side.

sendDeleteRequest void Send delete NA


request in the
client side.

sendCancelRequest void Send cancel NA


request in the
client side.

add_OnBeforeContextMenuOp Function name void Used to add NA


en(handler) the
OnBeforeCont
extMenuOpen
event
handlers.

remove_OnBeforeContextMenu Function name void Used to NA

© 2014 Syncfusion. All rights reserved. 756 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
Open(handler) remove the
OnBeforeCont
extMenuOpen
event
handlers.

add_OnContextMenuOpen(han Function name void Used to add NA


dler) the
OnContextMe
nuOpen event
handlers.

Function name void Used to NA


remove_OnContextMenuOpen( remove the
handler) OnContextMe
nuOpen event
handlers.

add_OnContextMenuItemClick( Function name void Used to add NA


handler) the
OnContextMe
nuItemClick
event
handlers.

remove_OnContextMenuItemCli Function name void Used to NA


ck(handler) remove the
OnContextMe
nuItemClick
event
handlers.

add_OnResizeHandleDblClick( Function name void Used to add NA


handler) the
OnResizeHan
dleDblClick
event
handlers.

remove_OnResizeHandleDblCli Function name void Used to NA


ck(handler) remove the
OnResizeHan

© 2014 Syncfusion. All rights reserved. 757 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
dleDblClick
event
handlers.

add_OnCustomUnboundCellCli Function name void Used to add NA


ckHandler(handler) the
OnCustomUn
boundCellClic
kevent
handlers.

remove_OnCustomUnboundCel Function name void Used to NA


lClickHandler(handler) remove the
OnCustomUn
boundCellClic
kevent
handlers.

add_OnContextMenuClose(han Function name void Used to add NA


dler) the
OnContextMe
nuClose event
handlers.

remove_OnContextMenuClose( Function name void Used to NA


handler) remove the
OnContextMe
nuClose event
handlers.

add_QueryCellInfo(handler) Function name void Used to add NA


the
QueryCellInfo
event
handlers.

remove_QueryCellInfo(handler) Function name void Used to NA


remove the
QueryCellInfo
event
handlers.

© 2014 Syncfusion. All rights reserved. 758 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
add_MergeCellInfo(handler) Function name void Used to add NA
the
MergeCellInfo
event
handlers.

remove_MergeCellInfo(handler) Function name void Used to NA


remove the
MergeCellInfo
event
handlers.

add_RowDataBound(handler) Function name void Used to add NA


the
RowDataBoun
d event
handlers.

remove_RowDataBound(handle Function name void Used to NA


r) remove the
RowDataBoun
d event
handlers.

add_OnCancel(handler) Function name void Used to add NA


the OnCancel
event
handlers.

remove_OnCancel(handler) Function name void Used to NA


remove the
OnCancel
event
handlers.

add_OnRecordAddNew(handler Function name void Used to add NA


) the
OnRecordAdd
New event
handlers.

remove_OnRecordAddNew(han Function name void Used to NA

© 2014 Syncfusion. All rights reserved. 759 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
dler) remove the
OnRecordAdd
New event
handlers.

add_OnRecordEdit(handler) Function name void Used to add NA


the
OnRecordEdit
event
handlers.

remove_OnRecordEdit(handler) Function name void Used to NA


remove the
OnRecordEdit
event
handlers.

add_OnCellEdit(handler) Function name void Used to add NA


the OnCellEdit
event
handlers.

remove_OnCellEdit(handler) Function name void Used to NA


remove the
OnCellEdit
event
handlers.

add_OnCellSave(handler) Function name void Used to add NA


the
OnCellSave
event
handlers.

remove_OnCellSave(handler) Function name void Used to NA


remove the
OnCellSave
event
handlers.

add_OnBulkSave(handler) Function name void Used to add NA


the

© 2014 Syncfusion. All rights reserved. 760 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
OnBulkSave
event
handlers.

remove_OnBulkSave(handler) Function name void Used to NA


remove the
OnBulkSave
event
handlers.

add_onResizingStart(handler) Function name void Used to add NA


the
onResizingSta
rt event
handlers.

remove_onResizingStart(handle Function name void Used to NA


r) remove the
onResizingSta
rt event
handlers.

add_onResizingEnd(handler) Function name void Used to add NA


the
onResizingEn
d event
handlers.

remove_onResizingEnd(handler Function name void Used to NA


) remove the
onResizingEn
d event
handlers.

add_Resized(handler) Function name void Used to add NA


the resized
event
handlers.

remove_Resized(handler) Function name void Used to NA


remove the
resized event

© 2014 Syncfusion. All rights reserved. 761 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
handlers.

add_onDragStart(handler) Function name void Used to add NA


the
onDragStart
event
handlers.

remove_onDragStart(handler) Function name void Used to NA


remove the
onDragStart
event
handlers.

add_beforeDrop(handler) Function name void Used to add NA


the
beforeDrop
event
handlers.

remove_beforeDrop(handler) Function name void Used to NA


remove the
beforeDrop
event
handlers.

add_afterDrop(handler) Function name void Used to add NA


the afterDrop
event
handlers.

remove_afterDrop(handler) Function name void Used to NA


remove the
afterDrop
event
handlers.

add_MouseUpDrop(handler) Function name void Used to add NA


the
MouseUpDrop
event
handlers.

© 2014 Syncfusion. All rights reserved. 762 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
remove_MouseUpDrop(handler Function name void Used to NA
) remove the
MouseUpDrop
event
handlers.

add_OnToolbarClickEvent(hand Function name void Used to add NA


ler) the
OnToolbarClic
kevent
handlers.

remove_OnToolbarClickEvent(h Function name void Used to NA


andler) remove the
OnToolbarClic
kevent
handlers.

add_OnRecordExpanding(handl Function name void Used to add NA


er) the
OnRecordExp
anding event
handlers.

remove_OnRecordExpanding(h Function name void Used to NA


andler) remove the
OnRecordExp
anding event
handlers.

add_OnRecordExpanded(handl Function name void Used to add NA


er) the
OnRecordExp
anded event
handlers.

remove_OnRecordExpanded(h Function name void Used to NA


andler) remove the
OnRecordExp
anded event
handlers.

© 2014 Syncfusion. All rights reserved. 763 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
add_OnRecordCollapsing(handl Function name void Used to add NA
er) the
OnRecordColl
apsing event
handlers.

remove_OnRecordCollapsing(h Function name void Used to NA


andler) remove the
OnRecordColl
apsing event
handlers.

add_OnRecordCollapsed(handl Function name void Used to add NA


er) the
OnRecordColl
apsed event
handlers.

remove_OnRecordCollapsed(h Function name void Used to NA


andler) remove the
OnRecordColl
apsed event
handlers.

add_OnRowHover (handler) Function name void Used to add NA


the
OnRowHover
event
handlers.

remove_OnRowHover(handler) Function name void Used to NA


remove the
OnRowHover
handler from
grid.

add_OnRowSelect (handler) Function name void Used to add NA


the
OnRowSelect
event
handlers.

© 2014 Syncfusion. All rights reserved. 764 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
remove_OnRowSelect(handler) Function name void Used to NA
remove the
OnRowSelect
handler from
grid.

add_OnDoubleClick(handler) Function name void Used to add NA


the
OnDoubleClic
k event
handlers.

remove_OnDoubleClick((handle Function name void Used to NA


r) remove the
OnDoubleClic
k handler from
grid.

add_OnRecordsUnselectionEve Function name void Used to add NA


nt(handler) the
OnRecordsUn
selectionEvent
event
handlers.

remove_OnRecordsUnSelectio Function name void Used to NA


nEvent(handler) remove the
OnRecordsUn
SelectionEven
t handler from
the grid.

add_OnRowsSelected(handler) Function name void Used to add NA


the
OnRowsSelec
ted event
handlers.

remove_OnRecordsUnSelectio Function name void Used to NA


nEvent(handler) remove the
OnRecordsUn
SelectionEven

© 2014 Syncfusion. All rights reserved. 765 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
t handler from
grid.

add_OnDroppingTarget(handler Function name void Used to add NA


) the
OnDroppingTa
rget event
handlers.

remove_OnDroppingTarget(han Function name void Used to NA


dler) remove the
OnDroppingTa
rget handler
from the grid.

add_OnDropTargetCompleted( Function name void Used to add NA


handler) the
OnDropTarget
Completed
event
handlers.

remove_OnDropTargetComplet Function name void Used to NA


ed(handler) remove the
OnDropTarget
Completed
handler from
the grid.

add_OnDroponGridRowsEvent( Function name void Used to add NA


handler) the
OnDroponGrid
RowsEvent
event
handlers.

remove_OnDroponGridRowsEv Function name void Used to NA


ent(handler) remove the
OnDroponGrid
RowsEvent
handler from
the grid.

© 2014 Syncfusion. All rights reserved. 766 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
add_OnDragonGridRowEvent(h Function name void Used to add NA
andler) the
OnDragonGrid
RowEvent
event
handlers.

remove_OnDragonGridRowEve Function name void Used to NA


nt(handler) remove the
OnDragonGrid
RowEvent
handler from
the grid.

add_OnLoad(handler) Function name void Used to add NA


the OnLoad
event
handlers.

remove_OnLoad(handler) Function name void Used to NA


remove the
OnLoad
handler from
the grid.

add_OnActionFailure(handler) Function name void Used to add NA


the
OnActionFailu
re event
handlers.

remove_OnActionFailure(handl Function name void Used to NA


er) remove the
OnActionFailu
re handler
from the grid.

add_OnActionBegin(handler) Function name void Used to add NA


the
OnActionBegi
n event
handlers.

© 2014 Syncfusion. All rights reserved. 767 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it Any other


property accepts dependenc
ies/sub-
properties
associated
remove_OnActionBegin(handler Function name void Used to NA
) remove the
OnActionBegi
n handler from
the grid.

add_OnActionSuccess(handler) Function name void Used to add NA


the
OnActionSucc
ess event
handlers.

remove_OnActionSuccess(han Function name void Used to NA


dler) remove the
OnActionSucc
ess handler
from grid.

add_OnActionComplete Function name void Used to NA


remove the
OnActionCom
plete handler
from the grid.

remove_OnActionComplete Function name void Used to NA


remove the
OnActionCom
plete handler
from grid.

Events
Name Description Arguments Reference
type
OnLoad Triggered when the grid is GridObject // returns grid NA
initialized in client side. object

OnActionFailure Triggered when the grid RequestType // returns NA


actions get failed. request type
Status // returns ajax

© 2014 Syncfusion. All rights reserved. 768 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Arguments Reference


type
request failure message

OnActionBegin Triggered for every grid Data // returns the record NA


action before its starts. object (JSON)

RequestType // returns
request type
MappingURL // returns
mapping url

OnActionSuccess Triggered for every grid RequestType // returns NA


action success event. request type

OnActionComplete Triggered for every grid RequestType // returns NA


action success event. request type

OnDragStart Triggered when column Drag Element NA


drag begins.

AfterDrop Triggered after the dragged Current cell // returns drag NA


column is dropped into element
another location.
From //drag index of the
column
To //drop index of the
column

Cellindex //drop index

BeforeDrop Triggered before the Current cell // returns drag NA


dragged column is dropped element
into another location.
From //drag index of the
column
To //drop index of the
column
Cellindex //drop index

MouseUpDrop Triggered when scrolling Current cell // returns drag NA


up on the dropped column. element

© 2014 Syncfusion. All rights reserved. 769 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Arguments Reference


type
From //drag index of the
column

To //drop index of the


column
Cellindex //drop index

OnContextMenuOpen Gets or sets the Handler Sender > Grid NA


name of the
Args > EventArgs
OnContextMenuOpen
event

OnContextMenuClose Gets or sets the Handler Sender > Grid NA


name of the
Args > EventArgs
OnContextMenuClose
event

OnContextMenuItemClick Gets or sets the Handler Sender > Grid NA


name of the
Args > EventArgs
OnContextMenuItemClick
event

OnBeforeContextMenuOpe Gets or sets the Handler Sender > Grid NA


n name of the
Args > EventArgs
OnBeforeContextMenuOpe
n event

OnToolbarClickEvent Used to add currentItem contains the NA


OnToolbarClick event current clicked toolbar item
handler
_currentItemId contains the
id of the current clicked
toolbar item

_currentItemIndex contains
the index of the current
clicked toolbar item
_disabled specifies whether
the current clicked toolbar
item is disabled or not.
_itemType specifies
whether the current clicked
toolbar item is a built-in item
or custom item.

© 2014 Syncfusion. All rights reserved. 770 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Arguments Reference


type
OnBulkSave Triggered before the  updatedRecords— NA
updated records are saved contains the list of
in the server side. updated records.

 deletedRecords—
contains the list of
deleted records.

 insertedRecords—
contains the list of
inserted records.

OnCancel Triggered before the  colObj— NA


updated records are columnObject
canceled for saving in the contains information
server side. about column
objects such as
name, type, header
text, etc.

 value—Contains the
value of the cell
being edited.

OnCellEdit Triggered before the edit  colObj— NA


form of the cell being columnObject
edited is rendered. contains information
about column
objects such as
name, type, header
text, etc.
 value—Contains the
value of the cell
being edited.

OnCellSave Triggered before the value  colObj— NA


of the particular cells being columnObject
edited are saved in the contains information
client side. about column
objects, such as

© 2014 Syncfusion. All rights reserved. 771 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Arguments Reference


type
name, type, header
text, etc.

 value—Contains the
updated value of
the cell.

OnRecordAddNew Triggered when new record String handler NA


is added.

OnRecordEdit Triggered when record is String handler NA


edited.

OnGridRowDragEvent Triggered while dragging in Event // returns event NA


any of grid rows.
Data // returns the record
object (JSON)

DragElement // returns drag


element

OnGridRowsDropEvent Triggered while dropped in Event // returns event NA


any of grid rows.
Data // returns the record
object (JSON)

DragElement // returns drag


element

OnRowDragStarted Triggered for every row in JSonRecord, // returns the NA


the grid when drag begins. record object (JSON)
Event // returns event

OnRowDropped Triggered for every row in Event // returns event NA


the grid when it is dropped.
Data // returns the record
object (JSON)

OnRowDropping Triggered for every row in Event // returns event NA


the grid when it is dropping
Data // returns the record
to other elements.
object (JSON)
OnRecordHoverEvent Triggered for every row in getRow() // contains the row NA
the grid when the mouse

© 2014 Syncfusion. All rights reserved. 772 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Arguments Reference


type
pointer is moved over it. object (DOM)

getRecord() // contains the


record object (JSON)
row // contains the row
object (DOM)

record // returns the record


object (JSON)
OnRecordSelectionEvent Triggered for every row in getRow() // contains the row NA
the grid when it is clicked. object (DOM)
getRecord() // contains the
record object (JSON)

row // contains the row


object (DOM)
record // returns the record
object (JSON)
OnRecordDoubleClickEven Triggered for every row in getRow() // contains the row NA
t
the grid when it is double- object (DOM)
clicked.
getRecord() // contains the
record object (JSON)

row // contains the row


object (DOM)
record // returns the record
object (JSON)
OnRecordsUnselectionEve Triggered for every row in getRow() // contains the row NA
nt
the grid when it is object (DOM)
deselected.
getRecord() // contains the
record object (JSON)
row // contains the row
object (DOM)
record // returns the record
object (JSON)

OnRecordCollapsed This event occurs in every String Handler NA


master row collapsed
event.

© 2014 Syncfusion. All rights reserved. 773 | Page


Essential Grid for ASP.NET MVC Classic

Name Description Arguments Reference


type
OnRecordCollapsing This event occurs before String Handler NA
every master row
collapses.

OnRecordExpanded This event occurs in every String Handler NA


master row expanded
event.

OnRecordExpanding This event occurs before String Handler NA


every master row expands.

OnResizingStart This event occurs when the String Handler NA


column resize starts.

OnResizingEnd This event occurs when the String Handler NA


column resizing is going to
end.

Resized This event occurs after the String Handler NA


column is resized.

4.23.1 Adding Handlers


There are three ways to add the handlers for the grid.
1. Through GridBuilder
2. Through GridPropertiesModel
3. Through Grid Client Object

4.23.1.1 Through GridBuilder


The following code sample illustrates adding handlers through GridBuilder.

View [ASPX]
<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.AllowDragAndDrop(true)

© 2014 Syncfusion. All rights reserved. 774 | Page


Essential Grid for ASP.NET MVC Classic

.Droppable(true)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
.ClientSideEvents(events =>
{
events.AfterDrop("AfterDrop");
events.BeforeDrop("BeforeDrop");
events.MouseUpDrop("MouseUpDrop");
events.OnActionBegin("OnActionBegin");
events.OnActionComplete("OnActionComplete");
events.OnActionFailure("OnActionFailure");
events.OnActionSuccess("OnActionSuccess");

events.OnBeforeContextMenuOpen("OnBeforeContextMenuOpen");
events.OnBulkSave("OnBulkSave");
events.OnCancel("OnCancel");
events.OnCellEdit("OnCellEdit");
events.OnCellSave("OnCellSave");

events.OnContextMenuClose("OnContextMenuClose");

events.OnContextMenuItemClick("OnContextMenuItemClick");

events.OnContextMenuOpen("OnContextMenuOpen");

events.OnCustomUnboundCellClickHandler("OnCustomUnboundCellClickHandler
");
events.OnDragStart("OnDragStart");

events.OnGridRowDragEvent("OnGridRowDragEvent");

© 2014 Syncfusion. All rights reserved. 775 | Page


Essential Grid for ASP.NET MVC Classic

events.OnGridRowsDropEvent("OnGridRowsDropEvent");
events.OnLoad("OnLoad");
events.OnRecordAddNew("OnRecordAddNew");

events.OnRecordCollapsed("OnRecordCollapsed");

events.OnRecordCollapsing("OnRecordCollapsing");

events.OnRecordDoubleClickEvent("OnRecordDoubleClickEvent");
events.OnRecordEdit("OnRecordEdit");
events.OnRecordExpanded("OnRecordExpanded");

events.OnRecordExpanding("OnRecordExpanding");

events.OnRecordHoverEvent("OnRecordHoverEvent");

events.OnRecordSelectionEvent("OnRecordSelectionEvent");

events.OnRecordsUnselectionEvent("OnRecordsUnselectionEvent");
events.OnResizingEnd("OnResizingEnd");
events.OnResizingStart("OnResizingStart");
events.OnRowDragStarted("OnRowDragStarted");
events.OnRowDropped("OnRowDropped");
events.OnRowDropping("OnRowDropping");

events.OnToolbarClickEvent("OnToolbarClickEvent");
events.Resized("Resized");
events.MergeCellInfo("MergeCellInfo");
events.QueryCellInfo("QueryCellInfo");
events.RowDataBound("RowDataBound");
})
%>

© 2014 Syncfusion. All rights reserved. 776 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]
@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
.ClientSideEvents(events =>
{
events.AfterDrop("AfterDrop");
events.BeforeDrop("BeforeDrop");
events.MouseUpDrop("MouseUpDrop");
events.OnActionBegin("OnActionBegin");
events.OnActionComplete("OnActionComplete");
events.OnActionFailure("OnActionFailure");
events.OnActionSuccess("OnActionSuccess");

events.OnBeforeContextMenuOpen("OnBeforeContextMenuOpen");
events.OnBulkSave("OnBulkSave");
events.OnCancel("OnCancel");
events.OnCellEdit("OnCellEdit");
events.OnCellSave("OnCellSave");

events.OnContextMenuClose("OnContextMenuClose");

events.OnContextMenuItemClick("OnContextMenuItemClick");

events.OnContextMenuOpen("OnContextMenuOpen");

events.OnCustomUnboundCellClickHandler("OnCustomUnboundCellClickHandler

© 2014 Syncfusion. All rights reserved. 777 | Page


Essential Grid for ASP.NET MVC Classic

");
events.OnDragStart("OnDragStart");

events.OnGridRowDragEvent("OnGridRowDragEvent");

events.OnGridRowsDropEvent("OnGridRowsDropEvent");
events.OnLoad("OnLoad");
events.OnRecordAddNew("OnRecordAddNew");

events.OnRecordCollapsed("OnRecordCollapsed");

events.OnRecordCollapsing("OnRecordCollapsing");

events.OnRecordDoubleClickEvent("OnRecordDoubleClickEvent");
events.OnRecordEdit("OnRecordEdit");
events.OnRecordExpanded("OnRecordExpanded");

events.OnRecordExpanding("OnRecordExpanding");

events.OnRecordHoverEvent("OnRecordHoverEvent");

events.OnRecordSelectionEvent("OnRecordSelectionEvent");

events.OnRecordsUnselectionEvent("OnRecordsUnselectionEvent");
events.OnResizingEnd("OnResizingEnd");
events.OnResizingStart("OnResizingStart");
events.OnRowDragStarted("OnRowDragStarted");
events.OnRowDropped("OnRowDropped");
events.OnRowDropping("OnRowDropping");

events.OnToolbarClickEvent("OnToolbarClickEvent");
events.Resized("Resized");
events.MergeCellInfo("MergeCellInfo");
events.QueryCellInfo("QueryCellInfo");
events.RowDataBound("RowDataBound");
}).Render();
}

© 2014 Syncfusion. All rights reserved. 778 | Page


Essential Grid for ASP.NET MVC Classic

4.23.1.2 Through GridPropertiesModel

The following code sample illustrates adding handlers through GridPropertiesModel.

GridPropertiesModel<Order> gridModel = new


GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,
Caption="Orders",
AllowPaging=true,
AllowSorting=true,
AllowFiltering=true,
AutoFormat=Skins.Sandune,
AfterDrop = "AfterDrop";
BeforeDrop = "BeforeDrop";
MouseUpDrop = "MouseUpDrop";
OnActionBegin = "OnActionBegin";
OnActionComplete = "OnActionComplete";
OnActionFailure = "OnActionFailure";
OnActionSuccess = "OnActionSuccess";
OnBeforeContextMenuOpen = "OnBeforeContextMenuOpen";
OnBulkSave = "OnBulkSave";
OnCancel = "OnCancel";
OnCellEdit = "OnCellEdit";
OnCellSave = "OnCellSave";
OnContextMenuClose = "OnContextMenuClose";
OnContextMenuItemClick = "OnContextMenuItemClick";
OnContextMenuOpen = "OnContextMenuOpen";
OnCustomUnboundCellClickHandler =
"OnCustomUnboundCellClickHandler";
OnDragStart = "OnDragStart";
OnGridRowDragEvent = "OnGridRowDragEvent";
OnGridRowsDropEvent = "OnGridRowsDropEvent";
OnLoad = "OnLoad";
OnRecordAddNew = "OnRecordAddNew";
OnRecordCollapsed = "OnRecordCollapsed";
OnRecordCollapsing = "OnRecordCollapsing";
OnRecordDoubleClickEvent = "OnRecordDoubleClickEvent";
OnRecordEdit = "OnRecordEdit";
OnRecordExpanded = "OnRecordExpanded";
OnRecordExpanding = "OnRecordExpanding";
OnRecordHoverEvent = "OnRecordHoverEvent";

© 2014 Syncfusion. All rights reserved. 779 | Page


Essential Grid for ASP.NET MVC Classic

OnRecordSelectionEvent = "OnRecordSelectionEvent";
OnRecordsUnselectionEvent =
"OnRecordsUnselectionEvent";
OnResizingEnd = "OnResizingEnd";
OnResizingStart = "OnResizingStart";
OnRowDragStarted = "OnRowDragStarted";
OnRowDropped = "OnRowDropped";
OnRowDropping = "OnRowDropping";
OnToolbarClickEvent = "OnToolbarClickEvent";
Resized = "Resized";
MergeCellInfo = "MergeCellInfo";
QueryCellInfo = "QueryCellInfo";
RowDataBound = "RowDataBound";

};

4.23.1.3 Through Grid Client Object

The following code sample illustrates adding handlers in client script.

var gridObj = $find("Grid1");

gridObj.add_OnBeforeContextMenuOpen(OnBeforeContextMenuOpen);
gridObj.add_OnContextMenuOpen(OnContextMenuOpen);
gridObj.add_OnContextMenuItemClick(OnContextMenuItemClick);
gridObj.add_OnResizeHandleDblClick(OnResizeHandleDblClick);
gridObj.add_OnCustomUnboundCellClickHandler(OnCustomUnboundCellClick);
gridObj.add_OnContextMenuClose(OnContextMenuClose);
gridObj.add_OnRowSelect(OnRowSelect);
gridObj.add_OnRowHover(OnRowHover);
gridObj.add_OnRowsSelected(OnRowsSelected);
gridObj.add_OnDroppingTarget(OnDroppingTarget);
gridObj.add_OnDropTargetCompleted(OnDropTargetCompleted);
gridObj.add_OnDoubleClick(OnDoubleClick);
gridObj.add_QueryCellInfo(QueryCellInfo);
gridObj.add_MergeCellInfo(MergeCellInfo);
gridObj.add_RowDataBound(RowDataBound);

© 2014 Syncfusion. All rights reserved. 780 | Page


Essential Grid for ASP.NET MVC Classic

gridObj.add_OnCancel(OnCancel);
gridObj.add_OnRecordAddNew(OnRecordAddNew);
gridObj.add_OnRecordEdit(OnRecordEdit);
gridObj.add_OnRecordsUnselectionEvent(OnRecordsUnselectionEvent);
gridObj.add_OnDroponGridRowsEvent(OnDroponGridRowsEvent);
gridObj.add_OnDragonGridRowEvent(OnDragonGridRowEvent);
gridObj.add_OnLoad(OnLoad);
gridObj.add_OnActionFailure(OnActionFailure);
gridObj.add_OnActionComplete(OnActionComplete);
gridObj.add_OnActionBegin(OnActionBegin);
gridObj.add_OnCellEdit(OnCellEdit);
gridObj.add_OnCellSave(OnCellSave);
gridObj.add_OnBulkSave(OnBulkSave);
gridObj.add_OnActionSuccess(OnActionSuccess);
gridObj.add_onResizingStart(onResizingStart);
gridObj.add_onResizingEnd(onResizingEnd);
gridObj.add_Resized(Resized);
gridObj.add_onDragStart(onDragStart);
gridObj.add_beforeDrop(beforeDrop);
gridObj.add_afterDrop(afterDrop);
gridObj.add_MouseUpDrop(MouseUpDrop);
gridObj.add_OnToolbarClickEvent(OnToolbarClickEvent);
gridObj.add_OnRecordExpanding(OnRecordExpanding);
gridObj.add_OnRecordExpanded(OnRecordExpanded);
gridObj.add_OnRecordCollapsing(OnRecordCollapsing);
gridObj.add_OnRecordCollapsed(OnRecordCollapsed);

4.23.2 Arguments details for the ClientSide events.

Events Arguments
OnCellEdit colObj:
OnCancel
AllowAutoWrap
OnCellSave

© 2014 Syncfusion. All rights reserved. 781 | Page


Essential Grid for ASP.NET MVC Classic

Events Arguments
OnRecordSelectionEvent AllowEditing
OnRecordsUnselectionEvent
AllowFilter
OnRecordHoverEvent
OnRecordDoubleClickEvent AllowFormatinEditMode

AllowSearching

cellEditType

CssName

FormatText

GridCommands

HeaderText

HtmlEncode

IsUnbound

JqueryFormat

maskEditParams

Member

Name

numericEditParams

percentEditParams

ResizeSettings

TemplateColumn

TemplateName

TextAlign

type

© 2014 Syncfusion. All rights reserved. 782 | Page


Essential Grid for ASP.NET MVC Classic

Events Arguments
Visible

Width

4.23.3 Removing Handlers from Grid


The following code sample illustrates removing handlers from grid object.

var gridObj = $find("Grid1");


gridObj.remove_OnBeforeContextMenuOpen(OnBeforeContextMenuOpen);
gridObj.remove_OnContextMenuOpen(OnContextMenuOpen);
gridObj.remove_OnContextMenuItemClick(OnContextMenuItemClick);
gridObj.remove_OnResizeHandleDblClick(OnResizeHandleDblClick);
gridObj.remove_OnCustomUnboundCellClickHandler(OnCustomUnboundCellClick
);
gridObj.remove_OnContextMenuClose(OnContextMenuClose);
gridObj.remove_OnRowSelect(OnRowSelect);
gridObj.remove_OnRowHover(OnRowHover);
gridObj.remove_OnRowsSelected(OnRowsSelected);
gridObj.remove_OnDroppingTarget(OnDroppingTarget);
gridObj.remove_OnDropTargetCompleted(OnDropTargetCompleted);
gridObj.remove_OnDoubleClick(OnDoubleClick);
gridObj.remove_QueryCellInfo(QueryCellInfo);
gridObj.remove_MergeCellInfo(MergeCellInfo);
gridObj.remove_RowDataBound(RowDataBound);
gridObj.remove_OnCancel(OnCancel);
gridObj.remove_OnRecordAddNew(OnRecordAddNew);
gridObj.remove_OnRecordEdit(OnRecordEdit);
gridObj.remove_OnRecordsUnselectionEvent(OnRecordsUnselectionEvent);
gridObj.remove_OnDroponGridRowsEvent(OnDroponGridRowsEvent);
gridObj.remove_OnDragonGridRowEvent(OnDragonGridRowEvent);
gridObj.remove_OnLoad(OnLoad);
gridObj.remove_OnActionFailure(OnActionFailure);
gridObj.remove_OnActionComplete(OnActionComplete);

© 2014 Syncfusion. All rights reserved. 783 | Page


Essential Grid for ASP.NET MVC Classic

gridObj.remove_OnActionBegin(OnActionBegin);
gridObj.remove_OnCellEdit(OnCellEdit);
gridObj.remove_OnCellSave(OnCellSave);
gridObj.remove_OnBulkSave(OnBulkSave);
gridObj.remove_OnActionSuccess(OnActionSuccess);
gridObj.remove_onResizingStart(onResizingStart);
gridObj.remove_onResizingEnd(onResizingEnd);
gridObj.remove_Resized(Resized);
gridObj.remove_onDragStart(onDragStart);
gridObj.remove_beforeDrop(beforeDrop);
gridObj.remove_afterDrop(afterDrop);
gridObj.remove_MouseUpDrop(MouseUpDrop);
gridObj.remove_OnToolbarClickEvent(OnToolbarClickEvent);
gridObj.remove_OnRecordExpanding(OnRecordExpanding);
gridObj.remove_OnRecordExpanded(OnRecordExpanded);
gridObj.remove_OnRecordCollapsing(OnRecordCollapsing);
gridObj.remove_OnRecordCollapsed(OnRecordCollapsed);

4.23.4 Expand/Collapse Grouped column


A grid grouped column can be expanded or collapsed from the client side. Add the following
code sample in the view page.
a. To collapse a grouped column details, use the following code in the view page.

<input type="button" onclick="collapse()" value="Collapse All" />


<script type="text/javascript">
function collapse() {
var gridObj = $find("OrderGrid");
// Client-side collapse all
gridObj.collapseAll();
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 784 | Page


Essential Grid for ASP.NET MVC Classic

Figure 255: CollapseAll()

a. To expand a grouped column details, use the following code in the view page.

<input type="button" onclick="expand ()" value="Expand All" />


<script type="text/javascript">
function expand () {
var gridObj = $find("OrderGrid");
// Client-side expand all
gridObj.expandAll();
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 785 | Page


Essential Grid for ASP.NET MVC Classic

Figure 256: ExpandAll()

4.23.5 Set Methods


4.23.5.1 Primary key collection
Using the primary key collection users can prevent the editing option for that particular column.
Include the following code sample in the view page to provide the primary key collection in the
client side.
a. To provide the primary key collection, include the following code sample in the view page.

<input type="button" onclick="setPrimaryKeys()" value="Set Primary


Keys" />
<script type="text/javascript">
function setPrimaryKeys() {
var gridobj = $find("OrderGrid");

gridobj.set_PrimaryKeys(["OrderID","CustomerID","ShipCity"]);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 786 | Page


Essential Grid for ASP.NET MVC Classic

Figure 257: OrderID, CustomerID and ShipCity columns are set as primary key

4.23.5.2 Current Page


Set the current page for the grid in the client side using the set_CurrentPage method .
Include the following code sample in the view page to set the current page for the pager in the
client side:
a. To set the current page for the pager, include the following code sample in the view page.

<input type="button" onclick="setCurrentpage()" value="Set Current


page" />
<script type="text/javascript">
function setCurrentpage() {
var gridobj = $find("OrderGrid");
gridobj.set_CurrentPage(3);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 787 | Page


Essential Grid for ASP.NET MVC Classic

Figure 258: Current page is set as 3

4.23.5.3 Page Size


Set the page size for the grid in the client side using the set_PageSize method.
Include the following code sample in the view page to set the page size for the pager in the client
side.
a. To set the page size for the pager, include the following code sample in the view page.

<input type="button" onclick="setCurrentpage()" value="Set Current


page" />
<script type="text/javascript">
function setCurrentpage() {
var gridobj = $find("OrderGrid");
gridobj.set_PageSize(3);
gridobj.sendPagingRequest();
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 788 | Page


Essential Grid for ASP.NET MVC Classic

Figure 259: Pagesize 5 is set to the pager

4.23.5.4 Direction for the Enter key


By default, when Enter is pressed, the RecordSelectionDown action takes place. The direction
of the Enter key can be set to one of the following options: Up, Down, Right, and Left.
Include the following code sample in the view page to set the direction when Enter is pressed.
<script type="text/javascript">
Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj.set_enterKey("Right");
})
</script>

Run the project. The grid will appear as shown below:

© 2014 Syncfusion. All rights reserved. 789 | Page


Essential Grid for ASP.NET MVC Classic

Figure 260: Selecting the Direction “Right” for the Enter Key

4.23.5.5 Direction for the Tab key


By default, when Tab is pressed, the RightCellSelection action takes place. The direction of the
Tab key can be set to one of the following options: Up, Down, Right, and Left.
Include the following code sample in the view page to set the direction when Tab is pressed.

<script type="text/javascript">
Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj.set_tabKey("Down");
})
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 790 | Page


Essential Grid for ASP.NET MVC Classic

Figure 261: Selecting Direction “Down” for TAB Key

4.23.6 Select and Deselect Methods


4.23.6.1 Row
The rows in a grid can be selected or deselected using the selectRow(rowIndex) or
deselectRow(rowIndex) methods.
Include the following code sample in the view page to enable the preceding client-side row
selection.
a. To select a row, include the following code sample in the view page.

<input type="button" onclick="selectGridRow()" value="Select


row" />

<script type="text/javascript">

function selectGridRow() {
var gridobj = $find("OrderGrid");
gridobj.selectRow(0);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 791 | Page


Essential Grid for ASP.NET MVC Classic

Figure 262: Selected Grid Row

b. To cancel the selection of the row, include the following code sample in the view page.

View
<input type="button" onclick="deSelectGridRow()"
value="Deselect Row" />

<script type="text/javascript">

function deSelectGridRow() {
var gridobj = $find("OrderGrid");
gridobj.deselectRow(0);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 792 | Page


Essential Grid for ASP.NET MVC Classic

Figure 263: deSelectGridRow()

4.23.6.2 Current Cell


The cells in a grid can be selected using the set_selectCell methods.
Include the following code sample in the view page to select the cell in the grid in the client side .
a. To select the cell, include the following code sample in the view page.

<input type="button" onclick="selectcell()" value="Select Cell" />


<script type="text/javascript">
function selectcell() {
var gridobj = $find("OrderGrid");
gridobj. get_SelectionManager().set_selectCell(2,1);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 793 | Page


Essential Grid for ASP.NET MVC Classic

Figure 264: The second row and first column cell is selected

4.23.6.3 Multiple rows in a Grid


You can select the multiple rows in a grid to perform various actions on it. Include the following
code sample in the view page to select the multiple grid.

<input type="button" onclick="selectMultipleRows()" value="Select


Multiple rows" />

<script type="text/javascript">
function selectMultipleRows() {
var gridobj = $find("OrderGrid");
gridobj. selectMutipleRows(2,7);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 794 | Page


Essential Grid for ASP.NET MVC Classic

Figure 265: Select Rows from the index 2 to 7

4.23.6.4 Entire Grid


You can select the entire grid to perform various actions on it. Include the following code sample
in the view page to select the entire grid.
<input type="button" onclick="selectGrid()" value="Select All" />

<script type="text/javascript">
function selectGrid() {
var gridobj = $find("OrderGrid");
gridobj.selectAll();
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 795 | Page


Essential Grid for ASP.NET MVC Classic

Figure 266: Selecting an Entire Grid

4.23.7 Show and Hide Methods


4.23.7.1 Row
You can show or hide rows in a grid by using the showRow(rowIndex) and hideRow(rowIndex)
methods.
The following code example illustrates how to enable the preceding client-side show and hide
rows operation.
a. To hide a row, use the following code in the view page.

View

<input type="button" onclick="hideGridRow()" value="Hide Row" />

<script type="text/javascript">
function hideGridRow() {
var gridobj = $find("OrderGrid");
gridobj.hideRow(0);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 796 | Page


Essential Grid for ASP.NET MVC Classic

Figure 267: Hide OrderID 10248 using hideGridRow()

b. To show a row, use the following code in the view page.

View
<input type="button" onclick="showGridRow()" value="Show
Row" />

<script type="text/javascript">

function showGridRow() {
var gridobj = $find("OrderGrid");
gridobj.showRow(0);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 797 | Page


Essential Grid for ASP.NET MVC Classic

Figure 268: showGridRow()

4.23.7.2 Column
The column can be hidden in two ways:
 By ColumnName
 By ColumnIndex

4.23.7.2.1 By ColumnName
You can show or hide columns in a grid by using the showColumn(columnName) and
hideColumn(columnName) methods.
The following code example illustrates how to enable the preceding client-side operation.
a. To show a column, add the following code to the view page:

View

<input type="button" onclick="showGridColumn()" value="Show


Column" />
<script type="text/javascript">

function showGridColumn() {
var gridobj = $find("OrderGrid");
gridobj.showColumn("OrderID");
}
</script>

© 2014 Syncfusion. All rights reserved. 798 | Page


Essential Grid for ASP.NET MVC Classic

b. To hide a column, add the following code to the view page:

View

<input type="button" onclick="hideGridColumn()" value="Hide


Column" />

<script type="text/javascript">

function hideGridColumn() {
var gridobj = $find("OrderGrid");
gridobj.hideColumn("OrderID");
}
</script>

4.23.7.2.2 By ColumnIndex
You can show or hide columns in a grid by using the showColumnByIndex(index) and
hideColumnByIndex(index) methods.
The following code example illustrates how to enable the preceding client-side operation.
a. To show a column, add the following code to the view page:

View

<input type="button" onclick="showGridColumn()" value="Show


ColumnByIndex" />
<script type="text/javascript">

function showGridColumn() {
var gridobj = $find("OrderGrid");
gridobj.showColumnByIndex(0);
}
</script>

© 2014 Syncfusion. All rights reserved. 799 | Page


Essential Grid for ASP.NET MVC Classic

a. To hide a column, add the following code to the view page:

View

<input type="button" onclick="hideGridColumn()" value="Hide


ColumnByIndex" />

<script type="text/javascript">

function hideGridColumn() {
var gridobj = $find("OrderGrid");
gridobj.hideColumnByIndex(0);
}
</script>

Figure 269: show the “OrderID” of the Grid using showColumnByIndex() and showColumn()

© 2014 Syncfusion. All rights reserved. 800 | Page


Essential Grid for ASP.NET MVC Classic

Figure 270: Hide the “OrderID” column using hideColumn() and hideColumnByIndex()

4.23.7.3 GroupDropArea
Show or hide the groupdroparea in a grid by using the set_ ShowGroupDropArea methods.
The following code example illustrates how to enable the preceding client-side
showGroupDropArea operation.
a. To show a GroupDropArea, use the following code in the view page.

View

<input type="button" onclick="showGroupDropArea()" value="Show


GroupDrop area" />

<script type="text/javascript">
function showGroupDropArea() {
var gridobj = $find("OrderGrid");
gridobj. set_ ShowGroupDropArea(true);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 801 | Page


Essential Grid for ASP.NET MVC Classic

Figure 271: showGroupDropArea()

b. To hide a row header, use the following code in the view page.

View
<input type="button" onclick="hideGroupDropArea()" value="Hide
GroupDrop area" />

<script type="text/javascript">
function hideGroupDropArea() {
var gridobj = $find("OrderGrid");
gridobj. set_ ShowGroupDropArea(false);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 802 | Page


Essential Grid for ASP.NET MVC Classic

Figure 272: hideGroupDropArea()

4.23.7.4 RowHeader
The row header in a grid can be hidden by using the set_ShowRowHeader methods.
The following code example illustrates how to disable the preceding client-side ShowRowHeader
operation.
a. To hide a row header, use the following code in the view page.

View
<input type="button" onclick="hideRowHeader()" value="Hide
RowHeader" />

<script type="text/javascript">

function hideRowHeader() {
var gridobj = $find("OrderGrid");
gridobj.set_ShowRowHeader(false);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 803 | Page


Essential Grid for ASP.NET MVC Classic

Figure 273: hideRowHeader()

4.23.8 Enable/Disable Methods


4.23.8.1 RowHover
You can enable or disable the row hover effect in a grid by using the set_ EnableRowHover
methods.
The following code example illustrates how to enable the preceding client-side EnableRowHover
operation.
a. To enable a rowhover, use the following code in the view page.

View

<input type="button" onclick="enableRowHover()" value="Enable RowHover"


/>

<script type="text/javascript">
function enableRowHover() {
var gridobj = $find("OrderGrid");
gridobj. set_ EnableRowHover(true);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 804 | Page


Essential Grid for ASP.NET MVC Classic

Figure 274: enableRowHover()

b. To disable a rowhover, use the following code in the view page.

View
<input type="button" onclick="disableRowHover()"
value="Disable RowHover" />

<script type="text/javascript">

function disableRowHover() {
var gridobj = $find("OrderGrid");
gridobj.set_ EnableRowHover(false);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 805 | Page


Essential Grid for ASP.NET MVC Classic

Figure 275: disableRowHover()

4.23.8.2 Editing functionality


The editing functionality in a grid can be enabled or disabled by using the set_ AllowEditing
methods.
The following code example illustrates how to enable the preceding client-side AllowEditing
operation.
a. To enable a row hover, use the following code in the view page.
View
<input type="button" onclick="enableEditing()" value="Enable Editing"
/>
<script type="text/javascript">
function enableEditing() {
var gridobj = $find("OrderGrid");
gridobj. set_ AllowEditing(true);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 806 | Page


Essential Grid for ASP.NET MVC Classic

Figure 276: enableEditing()

b. To disable editing, use the following code in the view page.

View
<input type="button" onclick="disableEditing()" value="Disable Editing"
/>
<script type="text/javascript">
function disableEditing () {
var gridobj = $find("OrderGrid");
gridobj.set_ AllowEditing(false);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 807 | Page


Essential Grid for ASP.NET MVC Classic

Figure 277: disableEditing()

4.23.8.3 Grouping functionality


The grouping functionality in a grid can be enabled or disabled by using the set_ AllowGrouping
methods.
The following code example illustrates how to enable the preceding client-side AllowGrouping
operation.
a. To enable a grouping, use the following code in the view page.
View
<input type="button" onclick="enableGrouping()" value="Enable Grouping"
/>
<script type="text/javascript">
function enableGrouping() {
var gridobj = $find("OrderGrid");
gridobj. set_ AllowGrouping(true);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 808 | Page


Essential Grid for ASP.NET MVC Classic

Figure 278: enableGrouping()

a. To disable a Grouping, use the following code in the view page.

View
<input type="button" onclick="disableGrouping()" value="Disable
Grouping" />
<script type="text/javascript">
function disableGrouping () {
var gridobj = $find("OrderGrid");
gridobj.set_ AllowGrouping(false);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 809 | Page


Essential Grid for ASP.NET MVC Classic

Figure 279: disableGrouping()

4.23.8.4 Paging functionality


Enable or disable the paging functionality in a grid by using the set_ AllowPaging methods.
The following code example illustrates how to enable the preceding client-side AllowPaging
operation.
a. To enable paging, use the following code in the view page.

View
<input type="button" onclick="enablePaging()" value="Enable Paging" />
<script type="text/javascript">
function enablePaging() {
var gridobj = $find("OrderGrid");
gridobj. set_ AllowPaging(true);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 810 | Page


Essential Grid for ASP.NET MVC Classic

Figure 280: enableGrouping()

b. To disable paging, use the following code in the view page.

View
<input type="button" onclick="disablePaging()" value="Disable Paging"
/>
<script type="text/javascript">
function disablePaging() {
var gridobj = $find("OrderGrid");
gridobj.set_ AllowPaging(false);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 811 | Page


Essential Grid for ASP.NET MVC Classic

Figure 281: disablePaging()

4.23.8.5 Selection functionality


Enable or disable the Selection functionality in a grid by using the set_ AllowSelection methods.
The following code example illustrates how to enable the preceding client-side AllowSelection
operation.
a. To enable Selection, use the following code in the view page.

View
<input type="button" onclick="enableSelection()" value="Enable
Selection" />
<script type="text/javascript">
function enableSelection() {
var gridobj = $find("OrderGrid");
gridobj. set_ AllowSelection(true);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 812 | Page


Essential Grid for ASP.NET MVC Classic

Figure 282: enableSelection()

b. To disable Selection, use the following code in the view page.

View
<input type="button" onclick="disableSelection()" value="Disable
Selection" />
<script type="text/javascript">
function disableSelection() {
var gridobj = $find("OrderGrid");
gridobj.set_ AllowSelection(false);
}
</script>

Run the project. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 813 | Page


Essential Grid for ASP.NET MVC Classic

Figure 283: disableSelection()

4.23.9 sampleCustomize Methods


4.23.9.1 Current Cell
You can customize the current cell using a client-side property. This property applies a CSS class
to the current cell.
Add the following code to the view page.

<style type="text/css">
.CustomCell
{
text-align: right;
font-weight: bold;
}
</style>
<script type="text/javascript">

Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");

gridObj.set_currentCellBackground("CustomCell");

})

© 2014 Syncfusion. All rights reserved. 814 | Page


Essential Grid for ASP.NET MVC Classic

</script>

Run the project. The grid will appear as shown below.

Figure 284: Client side Custom Formatting for Current Cell

4.23.9.2 Current Selected Area


You can customize the current selected area of the grid by using the
set_selectedAreaBackgroundColorCss property. This property applies a CSS class to the
selected area which can be a grid, cell, or row.
The code below illustrates this.

<style type="text/css">
.CustomRowColor
{
background-color: Yellow;
}
</style>
<script type="text/javascript">

Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");

gridObj.set_selectedAreaBackgroundColorCss("CustomRowColor"

© 2014 Syncfusion. All rights reserved. 815 | Page


Essential Grid for ASP.NET MVC Classic

);

})
</script>

Run the project. The grid will appear as shown below.

Figure 285: Client-Side Custom Formatting for Currently Selected Area

4.23.9.3 Current Selected Row Header


You can customize the current selected row header of the grid by using the
set_rowHeaderSelectionCss property. This property applies a CSS class to the selected row
header which can be a cell or row.
The code below illustrates this.

<style type="text/css">
.CustomRowHeaderColor
{
background-color: Yellow;
}

© 2014 Syncfusion. All rights reserved. 816 | Page


Essential Grid for ASP.NET MVC Classic

</style>
<script type="text/javascript">

Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");

gridObj.set_rowHeaderSelectionCss("CustomRowHeaderColor ");
})
</script>

Run the project. The grid will appear as shown below.

Figure 286: Client-Side Custom Formatting for the currently selected row header

4.23.9.4 Current Selected Column Header


You can customize the current selected row header of the grid by using the
set_columnHeaderSelectionCss property. This property applies a CSS class to the selected
row header which can be a cell or a row.
The code below illustrates this.
<style type="text/css">
.CustomColumnHeader
{
font-family: cursive;
font-size : 20px;

© 2014 Syncfusion. All rights reserved. 817 | Page


Essential Grid for ASP.NET MVC Classic

font-style : italic;
font-weight : bold;
}
</style>
<script type="text/javascript">

Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");

gridObj.set_columnHeaderSelectionCss("CustomColumnHeader");
})
</script>

Run the project. The grid will appear as shown below.

Figure 269: Client-Side Custom Formatting for the Currently Selected Column header

4.23.9.5 Clone element of a dragged column


The clone element of a dragged column of the grid can be customized using the set_CloneCss
property. This property applies a CSS class to the clone element.
The code below illustrates this:

<style type="text/css">
.CustomCloneElement

© 2014 Syncfusion. All rights reserved. 818 | Page


Essential Grid for ASP.NET MVC Classic

{
background : yellow;
}
</style>
<script type="text/javascript">

Sys.Application.add_load(function () {
var gridObj = $find("OrderGrid");
gridObj. set_CloneCss("CustomCloneElement");
})
</script>

Run the project. The grid will appear as shown below.

Figure 287: Client-side custom formatting for the clone element of a dragged column

4.23.10 Sorting Methods


4.23.10.1 Sorting
A grid column can be sorted from the client side. For sorting a particular column through the client
side, add the following code sample in the view page:

<input type="button" onclick="sortGrid()" value="Sort Grid"


/>
<script type="text/javascript">

© 2014 Syncfusion. All rights reserved. 819 | Page


Essential Grid for ASP.NET MVC Classic

function sortGrid() {
var gridObj = $find("OrderGrid");
// Client-side sorting using ColumnName, Sort
Direction
gridObj.DoSorting("OrderID", "Descending");
}
</script>

Run the project. The grid will appear as shown below:

Figure 288: Client-Side Sorting

4.23.10.2 Clear Sorting


A grid sorted column can be cleared from the client side. Clear sorting for a particular column
through the client side, add the following code sample in the view page.

<input type="button" onclick="clearSorting()" value="Clear


Sorting" />
<script type="text/javascript">

function clearSorting() {
var gridObj = $find("OrderGrid");
// Client-side clear sorting using ColumnName
gridObj. clearSortingforColumn("OrderID");

© 2014 Syncfusion. All rights reserved. 820 | Page


Essential Grid for ASP.NET MVC Classic

}
</script>

Run the project. The grid will appear as shown below:

Figure 272: Before clearing the sorting for the OrderID column

Figure 273: Clear sorting for the OrderID column

4.23.11 Grouping Methods


4.23.11.1 Group Column
A grid column can be grouped from the client side. For a particular column to be grouped through
the client side, add the following code sample in the view page:

© 2014 Syncfusion. All rights reserved. 821 | Page


Essential Grid for ASP.NET MVC Classic

<input type="button" onclick="groupColumn()" value="Group Column" />


<script type="text/javascript">
function groupColumn() {
var gridObj = $find("OrderGrid");
// Client-side group column using ColumnName
gridObj. GroupBy("CustomerID");
}
</script>

Run the project. The grid will appear as shown below.

Figure 274: GroupBy Column

4.23.11.2 Ungroup Column


A grouped grid column can be ungrouped from the client side. For a particular column to be
ungrouped through the client side, add the following code sample in the view page.
<input type="button" onclick="unGroupColumn()" value="UnGroup Column"
/>
<script type="text/javascript">
function unGroupColumn() {

© 2014 Syncfusion. All rights reserved. 822 | Page


Essential Grid for ASP.NET MVC Classic

var gridObj = $find("OrderGrid");


// Client-side ungroup column using ColumnName
gridObj.UnGroupBy("CustomerID");
}
</script>

Run the project. The grid will appear as shown below.

Figure 289: GroupBy Column

4.23.12 Reorder Method


4.23.12.1 ReOrder Columns
A grid column can be reordered from the client side. For a particular column can be reordered
through the client side, add the following code sample in the view page.

<input type="button" onclick="reOrderColumn()" value="ReOrder Column"


/>
<script type="text/javascript">
function reOrderColumn() {
var gridObj = $find("OrderGrid");
// Client-side reorder column using from and to index value
gridObj.set_dropColumn(5,1);
}
</script>

© 2014 Syncfusion. All rights reserved. 823 | Page


Essential Grid for ASP.NET MVC Classic

Run the project. The grid will appear as shown below.

Figure 290: Before reordering the ShipCountry Column

Figure 291: After reordering the ShipCountry Column

4.23.13 How to send the request to the Grid using External


Button
4.23.13.1 Searching Request
The “sendSearchingRequest” method is used to send the searching request in the client side
by using an external button.

© 2014 Syncfusion. All rights reserved. 824 | Page


Essential Grid for ASP.NET MVC Classic

For sending the searching request through the client side, add the following code sample in the
view page.

<input type="button" onclick="searchingRequest()" value=" Searching


Request" />
<script type="text/javascript">
function searchingRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendSearchingRequest();
}
</script>

4.23.13.2 Paging Request


The “sendPagingRequest” method is used to send the paging request in the client side by using
an external button.
For sending the paging request through the client side, add the following code sample in the view
page.

<input type="button" onclick="pagingRequest()" value=" Paging Request "


/>
<script type="text/javascript">
function pagingRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendPagingRequest();
}
</script>

4.23.13.3 Filtering Request


The “sendFilteringRequest” method is used to send the filtering request in the client side by
using an external button.
For sending the filtering request through the client side, add the following code sample in the view
page.

<input type="button" onclick="filteringRequest()" value=" Filtering


Request " />
<script type="text/javascript">
function filteringRequest() {

© 2014 Syncfusion. All rights reserved. 825 | Page


Essential Grid for ASP.NET MVC Classic

var gridObj = $find("OrderGrid");


gridObj.sendFilteringRequest();
}
</script>

4.23.13.4 Sorting Request


The “sendSortingRequest” method is used to send the sorting request in the client side by
using an external button.
For sending the sorting request through the client side, add the following code sample in the view
page.

<input type="button" onclick="sortingRequest()" value=" Sorting Request


" />
<script type="text/javascript">
function sortingRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendSortingRequest();
}
</script>

4.23.13.5 Grouping Request


The “sendGroupingRequest” method is used to send the grouping request in the client side by
using an external button.
For sending the grouping request through the client side, add the following code sample in the
view page.

<input type="button" onclick="groupingRequest()" value=" Grouping


Request " />
<script type="text/javascript">
function groupingRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendGroupingRequest();
}
</script>

© 2014 Syncfusion. All rights reserved. 826 | Page


Essential Grid for ASP.NET MVC Classic

4.23.13.6 Excel Export Request


The “sendExcelExportRequest” method is used to send the Excel export request in the client
side by using an external button instead of the toolbar button .
For sending the Excel export request through the client side, add the following code sample in the
view page.

<input type="button" onclick="excelExportRequest()" value=" Excel


Export Request " />
<script type="text/javascript">
function excelExportRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendExcelExportRequest();
}
</script>

4.23.13.7 Word Export Request


The “sendWordExportRequest” method is used to send the Word export request in the client
side by using an external button instead of the toolbar button.
For sending the Word export request through the client side, add the following code sample in the
view page.

<input type="button" onclick="wordExportRequest()" value=" Word Export


Request " />
<script type="text/javascript">
function wordExportRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendWordExportRequest();
}
</script>

4.23.13.8 PDF Export Request


The “sendPDFExportRequest” method is used to send the PDF export request in the client side
by using an external button instead of the toolbar button.
For sending the PDF export request through the client side, add the following code sample in the
view page.

<input type="button" onclick="pdfExportRequest()" value=" PDF Export

© 2014 Syncfusion. All rights reserved. 827 | Page


Essential Grid for ASP.NET MVC Classic

Request " />


<script type="text/javascript">
function pdfExportRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendPDFExportRequest();
}
</script>

4.23.13.9 AddNew Request


The “sendAddNewRequest” method is used to send the add new request in the client side by
using an external button instead of the toolbar button.
For sending the add new request through the client side, add the following code sample in the
view page.

<input type="button" onclick="addnewRequest()" value=" Add New Request


" />
<script type="text/javascript">
function addnewRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendAddNewRequest();
}
</script>

4.23.13.10 Editing Request


The “sendEditingRequest” method is used to send the editing request in the client side by using
an external button instead of the toolbar button.
For sending the editing request through the client side, add the following code sample in the view
page.

<input type="button" onclick="editingRequest()" value=" Editing Request


" />
<script type="text/javascript">
function editingRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendEditingRequest();
}

© 2014 Syncfusion. All rights reserved. 828 | Page


Essential Grid for ASP.NET MVC Classic

</script>

4.23.13.11 Save Request


The “sendSaveRequest” method is used to send the save request in the client side by using an
external button instead of the toolbar button.
For sending the save request through the client side, add the following code sample in the view
page.

<input type="button" onclick="saveRequest()" value=" Save Request " />


<script type="text/javascript">
function saveRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendSaveRequest();
}
</script>

4.23.13.12 Delete Request


The “sendDeleteRequest” method is used to send the delete request in the client side by using
an external button instead of the toolbar button.
For sending the delete request through the client side, add the following code sample in the view
page.

<input type="button" onclick="deleteRequest()" value=" Delete Request "


/>
<script type="text/javascript">
function deleteRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendDeleteRequest();
}
</script>

4.23.13.13 Cancel Request


The “sendCancelRequest” method is used to send the cancel request in the client side by using
an external button instead of the toolbar button.
For sending the cancel request through the client side, add the following code sample in the view
page.

© 2014 Syncfusion. All rights reserved. 829 | Page


Essential Grid for ASP.NET MVC Classic

<input type="button" onclick="cancelRequest()" value=" Cancel Request "


/>
<script type="text/javascript">
function cancelRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendCancelRequest();
}
</script>

4.23.13.14 Refresh Request


The “sendRefreshRequest” method is used to send the refresh request in the client side by
using an external button.
For sending the refresh request through the client side, add the following code sample in the view
page.

<input type="button" onclick="refreshRequest()" value=" refresh Request


" />
<script type="text/javascript">
function refreshRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendRefreshRequest();
}
</script>

4.23.13.15 HTML Action Request


The “sendHtmlActionRequest” method is used to send the HTML action request in the client
side by using an external button.
For sending the HTML action request through the client side, add the following code sample in
the view page.

<input type="button" onclick="htmlRequest()" value=" Html Action


Request " />
<script type="text/javascript">
function htmlRequest() {
var gridObj = $find("OrderGrid");
gridObj.sendHtmlActionRequest();

© 2014 Syncfusion. All rights reserved. 830 | Page


Essential Grid for ASP.NET MVC Classic

}
</script>

4.24 Passing Values between Grid Actions


The following properties and methods are used to pass values between grid actions.
Properties

Property Description Type of Value it Any other


property accepts dependencies/sub-
properties
associated
QueryParam Gets or sets the string
route values. This
route values are
passed between
grid actions.

Methods

Method Parameters Return type Description


QueryParam(string) String IGridBuilder<T> Used to get the route
value. This route
values are passed
between grid actions.

The following code samples illustrate the passing of values between grid actions.

4.24.1 Through GridBuilder

Specify the route values using QueryParam() method as shown below:


View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnableSorting()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.QueryParam("Category= 5")
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order

© 2014 Syncfusion. All rights reserved. 831 | Page


Essential Grid for ASP.NET MVC Classic

ID").Width(150);
columns.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(200);
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.EnableSorting()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.QueryParam("Category= 5")
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order
ID").Width(150);
columns.Add(p => p.CustomerID).HeaderText("Customer
ID").Width(200);
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{0:dd-MM-yyyy}");
}).Render();
}

The value passed in a category is shared among all other grid actions like paging requests,
sorting requests, grouping requests, group expand requests, and filtering requests.

4.24.2 Through GridPropertiesModel


Specify the route values using QueryParam property as shown below:

GridPropertiesModel<Order> model = new


GridPropertiesModel<Order>();
model.QueryParam = "Category=5";

The value passed in category is shared among all other grid actions like paging requests, sorting
requests, grouping requests, group expand requests, and filtering requests.

© 2014 Syncfusion. All rights reserved. 832 | Page


Essential Grid for ASP.NET MVC Classic

4.25 Column Templates

Templates allow you to customize the way data is presented in the grid. Using template columns,
you can display images, links, and so on. It will give a better look and feel to the data presented in
the grid. It is very simple as the user can directly specify the template for the column.

Use Case Scenarios

The user can display customized data inside columns using this feature.

Properties
Property Description Type of Value it accepts Any other
property dependencie
s/sub-
properties
associated
TemplateColumn Gets or sets the Boolean True/False NA
particular column,
indicating if it is a
template column or not.

TemplateName Gets or sets the name string string TemplateColum


of the template for a n
particular column, when
the TemplateColumn
property is set to true.

Sample Link

To access the sample link:


1. Click Dashboard.
2. Click Run samples to launch the ASP.NET MVC sample browser.
3. Select Templates>Column Templates Server Mode to view the column template
feature’s full-fledged demo.

4.25.1 Adding Template to the Grid Column in an Application

Column templates can be rendered in two ways:

© 2014 Syncfusion. All rights reserved. 833 | Page


Essential Grid for ASP.NET MVC Classic

1. By specifying the name of the template in the property TemplateName of the particular
column.
2. Rendering the template through the UIHint annotation attribute of the particular column. In
this case, set the TemplateColumn property to True. There is no need to set the
TemplateName property as the name of the template is specified through UIHint
annotation attribute of the particular column.

For example, refer to the following code samples.


Product.Cs [DTO class]

[UIHint("ProductTemplate"), Required]
public string Product
{
get;

set;

View [ASPX]

<%= Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.Product).HeaderText("Product").TemplateColumn(true);
column.Add(p => p.CustomerID).HeaderText("CustomerId");

})
%>

View [cshtml]

@{ Html.Syncfusion().Grid<Order>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.Product).HeaderText("Product").TemplateColumn(true);
column.Add(p => p.CustomerID).HeaderText("CustomerId");

}).Render();
}

© 2014 Syncfusion. All rights reserved. 834 | Page


Essential Grid for ASP.NET MVC Classic

In the code above, the “Product” column will render the template “ProductTemplate”.

4.25.1.1 Server Mode


To add templates to the grid column using server mode:

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. In the view, use its Model property in Datasource() to bind the data source.
4. To render the template for the particular column, set its TemplateColumn property to True.
View [ASPX]

<%= Html.Syncfusion().Grid<Employee>("Grid1")
.Datasource(Model)
.Caption("Employees")
.Column(column =>
{

column.Add("Employee").HeaderText("Photo").TemplateColumn(true).Templat
eName("EmployeeTemplate");
column.Add(p =>
p.FirstName).HeaderText("Name");
column.Add(p =>
p.HireDate).HeaderText("HireDate");
column.Add(p =>
p.Address).HeaderText("Address");
})
.EnablePaging()
.PageSettings(p=>p.PageSize(3).PageCount(3).PagerStyle(PagerStyle.PrevN
extAndManual))
.EnableSorting()
.AutoFormat(Skins.Marble)

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Employee>("Grid1")
.Datasource(Model)
.Caption("Employees")
.Column(column =>
{

column.Add("Employee").HeaderText("Photo").TemplateColumn(true).Templat
eName("EmployeeTemplate");
column.Add(p =>
p.FirstName).HeaderText("Name");
column.Add(p =>

© 2014 Syncfusion. All rights reserved. 835 | Page


Essential Grid for ASP.NET MVC Classic

p.HireDate).HeaderText("HireDate");
column.Add(p =>
p.Address).HeaderText("Address");
})
.EnablePaging()
.PageSettings(p=>p.PageSize(3).PageCount(3).PagerStyle(PagerStyle.PrevN
extAndManual))
.EnableSorting()
.AutoFormat(Skins.Marble).Render();

5. Create the template for the “Employee” column.

202.
“EmployeeTemplate.ascx”

<img alt="<%= Model.FirstName %>" src="<%=


Url.Content("/Content/Images/Employees/" + Model.EmployeeID +
".png")%>" style="width:175px" />

203.
“EmployeeTemplate.cshtml”

<img alt="@Model.FirstName"
src="@Url.Content("/Content/Images/Employees/" + Model.EmployeeID +
".png")" style="width:175px" />

204.
205.
6. Set its data source and render the view.
206.
Controller

/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Employees.ToList();
return View(data);
}

7. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 836 | Page


Essential Grid for ASP.NET MVC Classic

Figure 292:Grid with Column Template

4.25.1.2 JSON Mode


To add templates to the grid column using JSON Mode:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the JSON ActionMode using the ActionMode method.
5. To render the template for the particular column, set its TemplateColumn property to True.

207.
View [ASPX]

<%= Html.Syncfusion().Grid<Employee>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Employees")
.Column(column =>
{

© 2014 Syncfusion. All rights reserved. 837 | Page


Essential Grid for ASP.NET MVC Classic

column.Add("Employee").HeaderText("Photo").TemplateColumn(true).Templat
eName("EmployeeTemplate");
column.Add(p =>
p.FirstName).HeaderText("Name");
column.Add(p =>
p.HireDate).HeaderText("HireDate");
column.Add(p =>
p.Address).HeaderText("Address");
})
.EnablePaging()
.PageSettings(p=>p.PageSize(3).PageCount(3).PagerStyle(PagerStyle.PrevN
extAndManual))
.EnableSorting()
.AutoFormat(Skins.Marble)

%>

View [cshtml]

@{ Html.Syncfusion().Grid<Employee>("Grid1")
.ActionMode(ActionMode.JSON)
.Caption("Employees")
.Column(column =>
{

column.Add("Employee").HeaderText("Photo").TemplateColumn(true).Templat
eName("EmployeeTemplate");
column.Add(p =>
p.FirstName).HeaderText("Name");
column.Add(p =>
p.HireDate).HeaderText("HireDate");
column.Add(p =>
p.Address).HeaderText("Address");
})
.EnablePaging()
.PageSettings(p=>p.PageSize(3).PageCount(3).PagerStyle(PagerStyle.PrevN
extAndManual))
.EnableSorting()
.AutoFormat(Skins.Marble).Render();

208.
6. Create the template for the “Employee” column.
209.

© 2014 Syncfusion. All rights reserved. 838 | Page


Essential Grid for ASP.NET MVC Classic

“EmployeeTemplate.ascx”

<img alt="${FirstName}" src="<%=


Url.Content("~/Content/Images/Employees/${EmployeeID}.png")%>"
style="width:175px" />

210.
“EmployeeTemplate.cshtml”

<img alt="${FirstName}"
src="@Url.Content("~/Content/Images/Employees/${EmployeeID}.png")"
style=width: 175px;" />

In JSON mode, model binding can be done by using the following syntax.

Syntax: ${ColumnName}
Example: ${EmployeeID}
211.
1. Render the view.

Controller

public ActionResult Index()


{
return View();
}
212.
2. In order to render the data source for the grid, create a Post method for Index actions
and bind the data source to the grid as given in the following code block.
213.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Employess.ToList();
return data.GridJSONActions<Employee>();
}
214.
3. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 839 | Page


Essential Grid for ASP.NET MVC Classic

Figure 293: Grid with Column Template

4.26 Toolbar

Essential Grid provides toolbar support and it can be customized. It contains the following built-in
toolbar items:
 AddNew
 Delete
 Cancel
 Edit
 Update
 Custom
 Export

The custom toolbar items can be added by setting the ToolbarOptions ItemType property to
Custom.

© 2014 Syncfusion. All rights reserved. 840 | Page


Essential Grid for ASP.NET MVC Classic

Use Case Scenarios


The user can add custom toolbar items using this feature. It also facilitates more user interaction.

Sample Link

To access the sample link:


1. Click Dashboard.
2. Click Run Samples to launch the ASP.NET MVC sample browser.
3. Select Templates>Custom Toolbar to view the column template feature’s full-fledged
demo.

4.26.1 Adding the Grid Toolbar in an Application

Refer to the section: Concepts and Features>Editing.

4.26.2 Customizing the Grid Toolbar in an Application

4.26.2.1 Through GridBuilder

To customize the grid toolbar using GridBuilder:

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Create the Grid control in the view and configure its properties.
4. Set the OnToolbarClickEvent handler for handling the toolbar click events.

View [ASPX]

<%=Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>

© 2014 Syncfusion. All rights reserved. 841 | Page


Essential Grid for ASP.NET MVC Classic

p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
})

.ClientSideEvents(e =>
e.OnToolbarClickEvent("OnToolbarClickEvent"))

.ToolBar(tools =>
{
// Adding the custom toolbar items.
// Add(customItemtitle, customItemcaption,
customItemCssClass)
tools.Add("ExpandAll", "Expand", "ExpandItem")
.Add("CollapseAll", "Collapse", "CollapseItem")
.Add("Refresh", "Refresh", "Refresh");
})

%>

View [cshtml]

@{ Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p =>
p.OrderID).HeaderText("Order ID");
column.Add(p =>
p.CustomerID).HeaderText("Customer ID");
column.Add(p =>
p.EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
})

.ClientSideEvents(e =>
e.OnToolbarClickEvent("OnToolbarClickEvent"))

.ToolBar(tools =>
{
// Adding the custom toolbar items.
// Add(customItemtitle, customItemcaption, customItemCssClass)
tools.Add("ExpandAll", "Expand", "ExpandItem")
.Add("CollapseAll", "Collapse", "CollapseItem")
.Add("Refresh", "Refresh", "Refresh");
})

© 2014 Syncfusion. All rights reserved. 842 | Page


Essential Grid for ASP.NET MVC Classic

.Render();
}

5. Handle the OnToolbarClickEvent as shown in the code block.


215.

<script type="text/javascript">

function OnToolbarClickEvent(sender, args) {


//Handling the toolbar click event
}
</script>

216.
6. Render the view.

Controller

public ActionResult Index()


{
var data = new NorthwindDataContext().Orders;
return View(data);
}

7. Run the application. The grid will appear as shown below.


217.

Figure 294: Grid with Custom Toolbar

© 2014 Syncfusion. All rights reserved. 843 | Page


Essential Grid for ASP.NET MVC Classic

4.26.2.2 Through GridPropertiesModel


To customize the grid toolbar using GridPropertiesModel:

218. Create a model in the application (Refer to How to>Adding a Model to the Application).
219. Create a strongly typed view (Refer to How to>Strongly Typed View)
3. Add the following code in the Index.aspx file to create the Grid control in the view.
220.
View [ASPX]

<%=Html.Syncfusion().Grid<Order>("Grid1", column=>
{
column.Add(p =>
p.OrderID).HeaderText("OrderID");
column.Add(p =>
p.CustomerID).HeaderText("CustomerID");
column.Add(p => p.
EmployeeID).HeaderText("EmployeeID");
column.Add(p =>
p.ShipAddress).HeaderText("ShipAddress");
column.Add(p =>
p.ShipCountry).HeaderText("ShipCountry");
}));

%>

View [cshtml]

@( Html.Syncfusion().Grid<Order>("Grid1", column=>
{
column.Add(p => p.OrderID).HeaderText("OrderID");
column.Add(p => p.CustomerID).HeaderText("CustomerID");
column.Add(p => p.EmployeeID).HeaderText("EmployeeID");
column.Add(p => p.ShipAddress).HeaderText("ShipAddress");
column.Add(p => p.ShipCountry).HeaderText("ShipCountry");
})
)

221.
4. Create a GridPropertiesModel in the Index method and assign the grid properties in the
model. Set the OnToolbarClickEvent to handle the toolbar click event.
222.
Controller

GridPropertiesModel<Order> model = new


GridPropertiesModel<Order>()
{
DataSource = new NorthwindDataContext().Orders,

© 2014 Syncfusion. All rights reserved. 844 | Page


Essential Grid for ASP.NET MVC Classic

Caption = "Orders",
AllowPaging=true,
AllowSorting=true,
AllowGrouping=true,
AutoFormat = Skins.Sandune
};

model.ClientSideEvents.OnToolbarClickEvent =
"OnToolbarClickEvent";

ViewData["Grid1"] = model;

223.
5. To add custom toolbar items, configure the toolbar as given in the following code sample.
224.
Controller

// Configure the toolbar


ToolbarSettings toolbar = new ToolbarSettings();

toolbar.Enable = true;

// Add the add new, edit, delete, save, cancel button in


toolbar.

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Custom, Title = "ExpandAll", Caption = "Expand",
CssClass = "ExpandItem" });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Custom, Title = "CollapseAll", Caption = "Collapse",
CssClass = "CollapseItem" });

toolbar.Items.Add(new ToolbarOptions() { ItemType =


GridToolBarItems.Custom, Title = "Refresh", Caption = "Refresh",
CssClass = "Refresh" });

model.ToolBar = toolbar;
225.
6. Handle the OnToolbarClickEvent as shown below.
226.

<script type="text/javascript">

function OnToolbarClickEvent(sender, args) {


// Handling the toolbar click event.
}
</script>

227.

© 2014 Syncfusion. All rights reserved. 845 | Page


Essential Grid for ASP.NET MVC Classic

7. Run the application. The grid will appear as shown below.

Figure 295: Grid with Custom Toolbar

4.26.3 GridPropertiesModel Table

Property Description Type of property Value it Any other


accepts dependencies/sub-
properties
associated
Toolbar Gets or sets Class NA
the toolbar for
the grid.

Enable Used to Bool True/false


enable or
disable the
toolbar in grid.

Items Used to add List<ToolbarOptions> Any toolbar


the items to items
grid toolbars.

4.26.3.1 ToolbarOptions Table

The following table gives the properties of the ToolbarOptions class.

© 2014 Syncfusion. All rights reserved. 846 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type of Value it accepts Any other


property dependencies/su
b-properties
associated
ItemType Gets or sets the item type Enum GridToolBarItems.Ad
of the toolbar dNew
GridToolBarItems.De
lete
GridToolBarItems.Ca
ncel

GridToolBarItems.Ed
it
GridToolBarItems.Up
date

GridToolBarItems.Cu
stom
GridToolBarItems.Ex
port

Caption Gets or sets the caption string string


for the toolbar item.

Title Gets or sets the title for string string


the toolbar item.

CssClass Gets or sets the Custom string string


Css class for applying the
custom style for that item

Mapper Gets or sets the mapper List<ToolbarOpti Any toolbar items ItemType
for the toolbar item when ons>
the ItemType is set to
Export

4.26.4 Methods
The following table provides the methods of the ToolbarOptions class.

Method Method Return type Description

© 2014 Syncfusion. All rights reserved. 847 | Page


Essential Grid for ASP.NET MVC Classic

Method Method Return type Description


Add(Expression<Func<T, Expression IGridPrimaryKeyBuilder<T> Used to add
object>> expression) the primary
keys to grid

ToolBar(Action<IToolBarBuilder> Action<IToolbarbuilder> IEditingBuilder<T> Used to


toobar) toolbar configure the
toolbar in the
editing mode

Add(GridToolBarItems item) GridToolBarItems IToolBarBuilder Used to add


the toolbar
item to grid

Add(GridToolBarItems item, GridToolBarItems, IToolBarBuilder Used to add


string caption) string the toolbar
item with a
caption

Add(string customItemTitle, string, string IToolBarBuilder Used to add


string customItemCssClass) the custom
toolbar item
with title and
customCss
class

Add(GridToolBarItems item, GridToolBarItems, IToolBarBuilder Used to add


string caption, string mapper) string, string the toolbar
item with
caption and
mapper

Add(string customItemTitle, string, string, string IToolBarBuilder Used to add


string customItemCaption, string the custom
customItemCssClass) toolbar item
with title,
caption and
customCss
class

EnableToolbar(bool enable) Bool IToolBarBuilder Used to


enable or
disable the
toolbar in grid.

© 2014 Syncfusion. All rights reserved. 848 | Page


Essential Grid for ASP.NET MVC Classic

4.26.5 Events
The following table provides the events of the ToolbarOptions class.

Name Description Arguments Reference


type
OnToolbarClickEvent Used to add the _currentItem contains NA
OnToolbarClickEvent the current clicked
event handlers toolbar item
_currentItemId
contains the id of the
current clicked toolbar
item
_currentItemIndex
contains the index of
the current clicked
toolbar item

_disabled specifies
whether the current
clicked toolbar item is
disabled or not.

_itemType specifies
whether the current
clicked toolbar item is
a built-in item or
custom item.

4.27 MultiColumnDropDown

MultiColumnDropDown is a data-bound control used to display multiple columns of data


(presented in a tabular format) in a drop-down box. The data selected from the drop-down can be
displayed in the combo box as you define. You can customize the header, text box, and style
settings for the drop-down box.

© 2014 Syncfusion. All rights reserved. 849 | Page


Essential Grid for ASP.NET MVC Classic

Figure 296: MultiColumnDropDown

In the figure above, a student can see all the university course details like course fees, duration,
CGPA, course code, etc. But after selecting one, it is not necessary to show all the details.You
can simply display the Univerity Code, fees, and CGPA.

Key Features
1. Bind the data source directly to the control; it will generate columns accordingly. No further
steps are required.
2. The MultiColumnDropdown control has some predefined skins which can be controlled
through a single property setting.

Some of the available skins are as follows.


 Office 2007 Blue
 Office 2007 Black
 Office 2007 Silver
 Vista

4.27.1 Elaborate Structure of MultiColumnDropDown

The following image marks the important sections of the MultiColumnDropDown control.

© 2014 Syncfusion. All rights reserved. 850 | Page


Essential Grid for ASP.NET MVC Classic

Figure 297: Structure of MultiColumnDropDown Control

4.27.2 Adding Essential MultiColumnDropDown to an


Application

To know how to create an ASP.NET MVC application and add Essential Grid to the application,
refer to the Getting Started section.

This section guides you on creating a multicolumn drop-down which includes the following steps.
1. Create a MultiColumnDropDown control in the view and set the data source using the
Datasource() method.

228.
View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>

229.
230.
View [cshtml]

@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})

© 2014 Syncfusion. All rights reserved. 851 | Page


Essential Grid for ASP.NET MVC Classic

.Width(500)
.Text("--Select--")
)

2. Set its data source in ViewData and render the view.

Controller

/// <summary>
/// Used for rendering the multicolumn drop-down
initially.
/// </summary>
/// <returns>View page; it displays the multicolumn drop-
down.</returns>
public ActionResult Index()
{

ViewData["data"] = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList();
return View();
}

3. Run the application. The multicolumn drop-down will appear as shown below.

Figure 298: MultiColumnDropDown Control

A sample that demonstrates a basic MultiColumnDropdown control can be downloaded from the
following link:
http://help.syncfusion.com/Support/grid_mvc/v8.3.0.20/UG/MvcMultiColumnDropdownSample.zip

© 2014 Syncfusion. All rights reserved. 852 | Page


Essential Grid for ASP.NET MVC Classic

Note: The version number for the assemblies has been set to 8.3.0.20 in the Web.config file of
the attached sample. Please change the version number to the appropriate version in the Web-
2008.config or Web-2010.config files (available in root directory) and those will automatically be
updated in the Web.config file.

4.27.3 Concepts and Features

4.27.3.1 Data Binding


This section explains how to bind a data source to the MultiColumnDropDown control.
Properties

Property Description Type of Value it Any other


property accepts dependencies/sub-
properties
associated
DataSource Gets or sets the IEnumerable NA
data source to multi
column dropdown
control.

DisplayExpression Specifies the Integer array Any


column index integer
values in array array
format used to set
the result values
into Textbox.

AllowTextEdit Specifies edit text Boolean True/false


is editable or not.
Default value is
True.

Methods

Name Parameters Return type Descriptions


DataSource Skins IMultiColumnDropDownBuilder Used to set skins to
(IEnumerable) multi column
dropdown.

© 2014 Syncfusion. All rights reserved. 853 | Page


Essential Grid for ASP.NET MVC Classic

DisplayExpression(int[]) Integer array IMultiColumnDropdownBuilder Specifies the column


index values in array
format that is used to
set the result values
into Textbox.

AllowTextEdit(bool) bool IMultiColumnDropdownBuilder Specifies if edit text


is editable or not.
Default value is
True.

4.27.3.1.1 Through Builder

In order to work with this feature please follow the steps below.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the view create the MultiColumnDropDown control and specify the data source using the
Datasource() method.

View [ASPX]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiCol
umnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.Width(500)
.Text("--Select--")
%>

231.

View [cshtml]
@{
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.Width(500)
.Text("--Select--")
.Render();
}

2. Specify the display column indexes in array format using the DisplayExpression() method.
232.
View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro

© 2014 Syncfusion. All rights reserved. 854 | Page


Essential Grid for ASP.NET MVC Classic

pdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
%>

View [cshtml]
@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
)

3. Run the application. The grid will appear as shown below.

Figure 299: MultiColumnDropDown Control

4.27.3.1.2 Through MultiColumnDropDownModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create the MultiColumnDropdown control in the view.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult

© 2014 Syncfusion. All rights reserved. 855 | Page


Essential Grid for ASP.NET MVC Classic

iColumnDropDownModel) ViewData["dropdown"]) %>

View [cshtml]

@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))

3. Create an instance to MultiColumnDropdownModel and assign a data source using the


Datasource property.

// Create instance to MultiColumnDropDownModel and assign


properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
Width = 500
};

4. Specify the display column indexes in array format using the DisplayExpression property.

// Create instance to MultiColumnDropDownModel and assign


properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AutoFormat = Skins.Office2007Black
};

5. Pass the model to the view using ViewData().

// Pass the MultiColumnDropDownModel to the view using


ViewData().
ViewData["dropdown"] = dropdown;

© 2014 Syncfusion. All rights reserved. 856 | Page


Essential Grid for ASP.NET MVC Classic

6. Run the application. The grid will appear as shown below.

Figure 300: Multicolumn Drop-Down

4.27.3.2 Appearance
The MultiColumnDropDown control supports fifteen professional built-in skins. These skins can
be applied to the drop-down column to enhance the look and feel of the control.

 Office 2007Blue
 Office 2007Black
 Office 2007Silver
 Vista
 Almond
 Blend
 Blueberry
 Marble
 Metro
 Midnight
 Monochrome
 Olive
 Sandune
 Turquoise

© 2014 Syncfusion. All rights reserved. 857 | Page


Essential Grid for ASP.NET MVC Classic

Figure 301: MultiColumnDropDown Control Skins

Use Case Scenarios


The built-in skins provide users a very easy way to specify a visual style for the control (by setting
just a single property) that suits their application requirements.

Property

© 2014 Syncfusion. All rights reserved. 858 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type Type of Value it accepts Any other


the dependencie
property s/sub-
properties
associated
AutoFormat Used to apply ServerSid Enum Skins.Office2007Bl NA
auto format by e ue
using Skins
Skins.Office2007Bl
enumeration.
ack
The default
value is Skins.Office2007Sil
Office2007Blu ver
e. Skins.Vista

Skins.Almond
Skins.Blend
Skins.Blueberry

Skins.Marble
Skins.Metro

Skins.Midnight
Skins.Monochrome

Skins.Olive
Skins.Sandune
Skins.Turquoise
Skins.VS2010

Methods

Method Arguments Return type Description

AutoFormat Skins IMultiColumnDropDownBuilder Used to set skins to


(Skins) multi column
dropdown.

Sample Link
To access the sample link:

© 2014 Syncfusion. All rights reserved. 859 | Page


Essential Grid for ASP.NET MVC Classic

233. Go to Tools MVC Demos in the sample browser. Refer to Installation and
Deployment>Samples and Location.
234.
235. Select the Multi Column Drop-Down item in the demo list.
236.
3. Select any of the demos to view the MultiColumnDropDown full-fledged demo.
Skins can be applied to the MultiColumnDropDown control in two ways.

 Through Builder
 Through MultiColumnDropDownModel

4.27.3.2.1 Through Builder

In order to work with this feature please follow the steps below.
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the view, create the MultiColumnDropDown control and configure its properties.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>

View [cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")

3. Specify the skins using the AutoFormat() method.

View [ASPX]

© 2014 Syncfusion. All rights reserved. 860 | Page


Essential Grid for ASP.NET MVC Classic

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Sandune)
.Text("--Select--")
%>

View [cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Sandune)
.Text("--Select--")
)

4. Run the application. The grid will appear as shown below.

Figure 302: MultiColumnDropDown Control with Sandune Skin

4.27.3.2.2 Through MultiDropdownModel

© 2014 Syncfusion. All rights reserved. 861 | Page


Essential Grid for ASP.NET MVC Classic

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create MultiColumnDropdown control in the view.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))

3. Create an instance to MultiColumnDropdownModel and assign a Datasource to the


model.

Controller

// Create instance to MultiColumnDropDownModel and assign its


properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500
};

4. Specify the skin using the AutoFormat property.


237.
Controller

// Create instance to MultiColumnDropDownModel and assign properties.


MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",

© 2014 Syncfusion. All rights reserved. 862 | Page


Essential Grid for ASP.NET MVC Classic

DisplayExpression = new int[3] { 2, 3, 5 },


Width = 500,
AutoFormat = Skins.Office2007Black
};

5. Pass the model to the view using ViewData()

Controller

// Pass the MultiColumnDropDownModel to View using ViewData()


ViewData["dropdown"] = dropdown;

6. Run the application. The grid will appear as shown below.


238.

Figure 303: MultiColumnDropDown Control with Office2007Black Skin

4.27.3.3 RightToLeft
The MultiColumnDropDown control now supports a full-fledged right-to-left mode which aligns
content in the control from right to left.
Use Case Scenarios
The RightToLeft property is used for international applications where the language is written
from right to left, such as Hebrew or Arabic. When this property is set to True, the
MultiColumnDropDown control will be displayed from right to left.

Enabling right-to-left support can be done in two ways:


 Builder

© 2014 Syncfusion. All rights reserved. 863 | Page


Essential Grid for ASP.NET MVC Classic

 MultiColumnDropDownModel

4.27.3.3.1 Through Builder


1. To enable right-to-left support using Builder: Create a model in the application. Refer to
How to>Adding a Model to the Application.
2. In the view, create the MultiColumnDropDown control and configure its properties.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>

View [cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
)

3. Enable/disable right-to-left mode using the RightToLeft() method.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.RightToLeft(true)
.Text("--Select--")
%>

© 2014 Syncfusion. All rights reserved. 864 | Page


Essential Grid for ASP.NET MVC Classic

View [cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.RightToLeft(true)
.Text("--Select--")
)

4. Set its data source and render the view.

Controller

/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page; it displays the
MultiColumnDropDown.</returns>
public ActionResult Index()
{

var Data = new


StudentDataContext().AutoFormatStudent.Take(200);
ViewData["data"] = Data;
return View(Data);
}

5. Run the application. The MultiColumnDropDown will appear as shown below.

© 2014 Syncfusion. All rights reserved. 865 | Page


Essential Grid for ASP.NET MVC Classic

Figure 304: Right-To-Left Enabled MultiColumnDropDown Control

4.27.3.3.2 Through MultiColumnDropDownModel


To enable right-to-left support using MultiColumnDropDownModel:
1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. Create the MultiColumnDropDown control in the view.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))

3. Create an instance for MultiColumnDropDownModel and assign Datasource to the


model.

Controller
// Create instance to MultiColumnDropDown model and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()

© 2014 Syncfusion. All rights reserved. 866 | Page


Essential Grid for ASP.NET MVC Classic

{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500
};

1. Enable/disable right-to-left mode using the RightToLeft property.

Controller

// Create instance to MultiColumnDropDownMmodel and assign properties.


MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
RightToLeft = true
};

2. Pass the model to the view using ViewData().

Controller
// Pass the MultiColumnDropDownModel to view using ViewData()
ViewData["dropdown"] = dropdown;

3. Run the application. The MultiColumnDropDown will appear as shown below.

© 2014 Syncfusion. All rights reserved. 867 | Page


Essential Grid for ASP.NET MVC Classic

Figure 305: Right-To-Left Enabled MultiColumnDropDown Control

Mozilla Layout Scrollbar Side

In the Mozilla browser, the side the scroll bar appears on can be configured in right-to-left (RTL)
and left-to-right (LTR) modes. The following are the options to configure ScrollbarSide.
Presently, the MultiColumnDropDown control supports both sides of the scrollbar in RTL mode
using the MozillaLayoutScrollbarSide property.

 0—In RTL, right-side scroll bar. In LTR, right-side scroll bar.


 1—In RTL, left-side scroll bar. In LTR, right-side scroll bar.
 2—In RTL, right-side scroll bar. In LTR, left-side scroll bar

The following steps are necessary to configure the scroll bar side in the Mozilla browser.
1. Type the URL about:config in the Mozilla browser and press ENTER to configure the
settings of the Mozilla browser.

© 2014 Syncfusion. All rights reserved. 868 | Page


Essential Grid for ASP.NET MVC Classic

Figure 306: about:config

2. Type layout.scrollbar in the Filter: text box and set the value to 1. The default value is 0.

© 2014 Syncfusion. All rights reserved. 869 | Page


Essential Grid for ASP.NET MVC Classic

Figure 307: Setting Scroll Bar Side

3. Now MultiColumnDropDown alignment issue will rise as shown in the following


screenshot.

Figure 308: Alignment Issue

Now set the MozillaLayoutScrollbarSide to LayoutScrollbarSide.Left. Then


MultiColumnDropDown will look as shown in the following screenshot.

© 2014 Syncfusion. All rights reserved. 870 | Page


Essential Grid for ASP.NET MVC Classic

Figure 309: Alignment Issue Fixed

Properties

Property Description Type Type of Value it Any other


the accepts dependenci
property es/sub-
properties
associated
RightToLeft Used to enable Server Boolean True/false NA
the Side
RightToLeft
mode in
MultiColumnDr
opDown

MozillaLayoutScr Used to set the Server LayoutScroll LayoutScrollbar RightToLeft


ollbarSide Layout Side barSide Side.Left
scrollbarside of
LayoutScrollbar
Mozilla
Side.Right
browser.

Methods

Method Argument Return type Descripti Reference links


s on

© 2014 Syncfusion. All rights reserved. 871 | Page


Essential Grid for ASP.NET MVC Classic

RightToLeft(Boolean) Boolean IMultiColumnDr Used to NA


opDownBuilder enable the
RightToLeft
mode in
MultiColum
nDropDown

MozillaLayoutScrollbar LayoutScroll IMultiColumnDr Used to set MozillaLayoutScrollb


Side(LayoutScrollbarSi barSide opDownBuilder the Layout arSide
de) scrollbarsid
e of Mozilla
browser.

Sample Link
To access the sample link:
1. Go to Tools MVC Demos in the sample browser. Refer to Installation and
Deployment>Samples and Location.
2. Select the Multi Column Drop-Down on the left side Accordion.
3. Select any of the demos to view the MultiColumnDropDown full demo.

4.27.3.4 Setting the Orientation


The drop-down menu in the MultiColumnDropDown control can be aligned in various positions.
The customization can be performed on two levels, i.e on the position of the drop-down menu and
the order of the content.
Properties
Property Description Type of Value it accepts Any other
property dependencies/s
ub-properties
associated
PopupDirection Gets or Sets the Enum GenericDropDownPopup NA
Popup direction Direction
of the multi
.Down
column
dropdown GenericDropDownPopup
content. Direction
.up

Methods

© 2014 Syncfusion. All rights reserved. 872 | Page


Essential Grid for ASP.NET MVC Classic

Method Parameters Return type Descriptions

PopupDirection(GenericDrop GenericDropDownPopu IMultiColumnDro Used to set popup direction


DownPopupDirection) pDirection pDownBuilder for mulicolumn dropdown.

4.27.3.4.1 Through Builder

In order to work with this feature, follow the steps below:


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the view, create the MultiColumnDropDown control and configure its properties.

239.
View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
)

© 2014 Syncfusion. All rights reserved. 873 | Page


Essential Grid for ASP.NET MVC Classic

3. Specify the pop-up direction using the PopupDirection() method.


240.
View[Aspx]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.PopupDirection(GenericDropDownPopupDirection.Up)
.Text("--Select--")
%>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdo
wn")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.PopupDirection(GenericDropDownPopupDirection.Up)
.Text("--Select--")
)

Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 874 | Page


Essential Grid for ASP.NET MVC Classic

Figure 310: MultiColumnDropDown Control with Upward Direction

4.27.3.4.2 Through MultiDropDownModel

241. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create the MultiColumnDropDown control in the view.
242.
View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))

3. Create an instance to MultiColumnDropdownModel and assign a data source to the


model.
243.
// Create instance to MultiColumnDropDownModel and assign
properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },

© 2014 Syncfusion. All rights reserved. 875 | Page


Essential Grid for ASP.NET MVC Classic

Width = 500
};

4. Specify the pop-up direction using the PopupDirection property.


244.
// Create instance to MultiColumnDropDownMmodel and assign
properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AutoFormat = Skins.Office2007Black,
PopupDirection=GenericDropDownPopupDirection.Up
};

5. Pass the model to vthe iew using ViewData().


245.
// Pass the MultiColumnDropDownModel to the view using
ViewData()
ViewData["dropdown"] = dropdown;

6. Run the application. The grid will appear as shown below.

Figure 311: Multicolumn Drop-down with Upward Direction

© 2014 Syncfusion. All rights reserved. 876 | Page


Essential Grid for ASP.NET MVC Classic

4.27.3.5 Defining the Display Conditions


Generic drop-downs support customizing the display conditions.
Properties

Name Description Type of Value it Default Dependency


property accepts value

InitiallyPopupShown When set to bool true/false false NA


True, it
displays the
pop up panel
on page load.

Text Defines the string alphanumeric "" NA


text to be
displayed in
the text box on
page load.

Methods
Method Parameters Return type Descriptions
InitiallyPopupShown(bool) bool IMultiColumnDropDownBuilder When set to True,
it displays the pop
up panel on page
load.

Text(string) string IMultiColumnDropDownBuilder Defines the text to


be displayed in the
text box on page
load.

To open the panel on page load follow the steps below:

4.27.3.5.1 Through Builder


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the view, create the MultiColumnDropDown control and configure its properties.
246.
View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiCol
umnDropdown")
.Datasource((IEnumerable) ViewData["data"])

© 2014 Syncfusion. All rights reserved. 877 | Page


Essential Grid for ASP.NET MVC Classic

.DisplayExpression(new int[] {2, 3, 5})


.Width(500)
.Text("--Select--")
%>

View [cshtml]

@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
)

3. Configure the InitiallyPopupShown() method.


247.
View[Aspx]
<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiCol
umnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.InitiallyPopupShown(true)
%>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumn
Dropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.InitiallyPopupShown(true)
)

4. Specify the default text box value using the Text() method.
248.
View [Aspx]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdo
wn")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})

© 2014 Syncfusion. All rights reserved. 878 | Page


Essential Grid for ASP.NET MVC Classic

.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
.InitiallyPopupShown(true)
%>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
.InitiallyPopupShown(true))

5. Run the application. The multicolumn pop-up panel will open on page load and will appear
as shown below.

Figure 312: Multicolumn Drop-down on Initial Page Load

4.27.3.5.2 Through MultiDropdownModel

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create the MultiColumnDropDown control in the view.

249.
View [ASPX]

© 2014 Syncfusion. All rights reserved. 879 | Page


Essential Grid for ASP.NET MVC Classic

<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))

3. Create an instance to MultiColumnDropDownModel and assign a data source to the model.


250.
// Create instance to MultiColumnDropDownModel and assign
properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500
};

4. To display the pop-up panel when the page loads, use the InitiallyPopupShown property.
251.
// Create instance to MultiColumnDropDownModel and assign
properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AutoFormat = Skins.Office2007Black,
InitiallyPopupShown=true
};

5. Specify the default text box value by using the Text property.
252.
// Create instance to MultiColumnDropDownModel and assign
properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{

© 2014 Syncfusion. All rights reserved. 880 | Page


Essential Grid for ASP.NET MVC Classic

Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AutoFormat = Skins.Office2007Black,
InitiallyPopupShown=true
};

6. Pass the model to the view using ViewData().


253.
// Pass the MultiColumnDropDownModel to the view using
ViewData()
ViewData["dropdown"] = dropdown;

7. Run the application. The multicolumn pop-up panel will open when the page loads and will
appear as shown below.

Figure 313: Multicolumn Drop-down on Initial Page Load

4.27.3.6 Column Mapping


The MultiColumnDropDown control also supports column mapping. Column mapping also
includes setting the header text of the column, visibility of the column, width of the column,
enabling and disabling sorting, formatting the text, and so on.

Use Case Scenarios


Column mapping allows you to filter columns in the bound table so that you can choose the
columns that need to be displayed.

© 2014 Syncfusion. All rights reserved. 881 | Page


Essential Grid for ASP.NET MVC Classic

Column mapping can be performed in two ways:


 Through Builder
 Through MultiColumnDropDownModel

4.27.3.6.1 Through Builder


1. To perform column mapping using Builder:Create a model in the application. Refer to
How to>Adding a Model to the Application.
2. Create a strongly typed view. Refer to How to>Strongly Typed View.
3. In the view, use the Model property Datasource() to bind the data source.
4. Map the columns using the Columns method and Add method and set the HeaderText,
Format, AllowSorting, Width, and Visible, and so on.
View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pDown")
.Datasource(Model)
.DisplayExpression(new int[] { 0,1,3 })
.AllowSorting(true)
.Columns(col => {
col.Add(m =>
m.UniversityCode).HeaderText(“UnivCode”);
col.Add(m => m.Title).Width(150);
col.Add(m =>
m.CourseFees).AllowSorting(false);
col.Add(m => m.CGPA);
})
%>

View [cshtml]

@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDo
wn")
.Datasource(Model)
.DisplayExpression(new int[] { 0,1,3 })
.AllowSorting(true)
.Columns(col => {
col.Add(m =>
m.UniversityCode).HeaderText(“UnivCode”);
col.Add(m => m.Title).Width(150);
col.Add(m =>

© 2014 Syncfusion. All rights reserved. 882 | Page


Essential Grid for ASP.NET MVC Classic

m.CourseFees).AllowSorting(false);
col.Add(m => m.CGPA);
})
)

5. Set its data source and render the view.

Controller

/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page; it displays the
MultiColumnDropDown.</returns>
public ActionResult Index()
{

var Data = new


StudentDataContext().AutoFormatStudent.Take(200);
return View(Data);
}

6. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to the grid as shown in the following code sample.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{

var Data = new


StudentDataContext().AutoFormatStudent.Take(20);
return Data.GridActions<Student>();
}

7. Run the application. The MultiColumnDropDown will appear as shown in the following
screenshot.

© 2014 Syncfusion. All rights reserved. 883 | Page


Essential Grid for ASP.NET MVC Classic

Figure 314: MultiColumnDropDown with HeaderText “UnivCode” and the Width of the Title Column Set to
150px

4.27.3.6.2 Through MultiColumnDropDownModel


To perform column mapping using MultiColumnDropDownModel:

1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. Add the following code in the Index.aspx file to create the MultiColumnDropDown
control in the view.
View [ASPX]
<%=
Html.Syncfusion().MultiColumnDropDown<MvcSampleApplication.Models.Stude
nt>("MulticolumnControl1", "DropDownModel", col =>
{
col.Add(m => m.UniversityCode).HeaderText("UnivCode");
col.Add(m => m.Title).Width(150);
col.Add(m => m.CourseFees).AllowSorting(false);
col.Add(m => m.CGPA);

})%>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<MvcSampleApplication.Models.Stude
nt>("MulticolumnControl1", "DropDownModel", col =>

© 2014 Syncfusion. All rights reserved. 884 | Page


Essential Grid for ASP.NET MVC Classic

{
col.Add(m => m.UniversityCode).HeaderText("UnivCode");
col.Add(m => m.Title).Width(150);
col.Add(m => m.CourseFees).AllowSorting(false);
col.Add(m => m.CGPA);
})
)

3. Create a MultiColumnDropDownModel in Index action. Assign


MultiColumnDropDown properties in this model and pass the model from the controller
to the view using ViewData class as in step 6.
4. Set the DataSource and DisplayExpression as shown in the following code sample.

Controller

AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(MultiColumnDropDownModel<Student>
dropdown)
{
dropdown.DataSource = new
StudentDataContext().AutoFormatStudent.Take(30);
dropdown.DisplayExpression = new int[2] { 2, 3 };
ViewData["DropDownModel"] = dropdown;

return PartialView("MultiColumnDropDownPartialView");
}

5. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to MultiColumnDropDown as shown in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}

6. Run the application. The MultiColumnDropDown control will appear as shown in the
following screenshot.

© 2014 Syncfusion. All rights reserved. 885 | Page


Essential Grid for ASP.NET MVC Classic

Figure 315: MultiColumnDropDown with HeaderText “UnivCode” and Width of Title Column set to 150px

Properties

Property Description Type Type of Value Any other


the it dependencies/su
propert accept b-properties
y s associated
Visible Used to set the ServerSid Boolean True/Fals NA
visibility of the e e
column.

Width Used to set the width Server Unit Numeric NA


of the column. Side Value

AllowSortin If AllowSorting Server Boolean True/Fals AllowSorting property


g property of Side e of
MultiColumnDropDo MultiColumnDropDo
wn is true, wn
AllowSorting property
of all the columns will
be set to true. It is
used to
enable/disable
sorting for the

© 2014 Syncfusion. All rights reserved. 886 | Page


Essential Grid for ASP.NET MVC Classic

Property Description Type Type of Value Any other


the it dependencies/su
propert accept b-properties
y s associated
specified column.

HeaderTex Used to set the Server String Any NA


t HeaderText of the Side String
column.

Format Used to format the Server String Any NA


value of the column side string

IsUnbound Used to check Server String Any NA


whether the column Side string
is bound or not.

Sample Link
To access the samples:
1. Go to Tools MVC Demos in the sample browser. Refer to Installation and
Deployment>Samples and Location.
254.
2. Select the Multi Column Drop-Down on the left side Accordion.
255.
3. Select any of the demos to view the MultiColumnDropDown full-fledged demo.

4.27.3.7 Client-Side Events


This section details the client-side events raised by the MultiColumnDropDown control.
Properties

Name Description Type of Value it Dependency


property accepts

ClientSideOnBeforePopup Used to add the clientside string alphanumeric NA


Shown ClientSideOnBeforePopupS
hown event to control.

ClientSideOnPopupHidden Used to add the clientside string alphanumeric NA


ClientSideOnPopupHidden
event to control.

ClientSideOnPopupShown Used to add the clientside string alphanumeric NA


ClientSideOnPopupShown

© 2014 Syncfusion. All rights reserved. 887 | Page


Essential Grid for ASP.NET MVC Classic

event to control.

ClientSideOnSelect Used to add the clientside string alphanumeric NA


ClientSideOnSelect event
to control.

ClientSideOnTextChanged Used to add the clientside string alphanumeric NA


ClientSideOnTextChanged
event to control.

Methods

Method Paramet Return type Descriptions


ers
ClientSideOnBeforePopupShow Function IMultiColumnDropDown Used to add the
n(handler) name in Builder client-side
string OnBeforePopupSho
format wn event to the
control.

ClientSideOnPopupHidden(handl Function IMultiColumnDropDown Used to add the


er) name in Builder client-side
string ClientSideOnPopup
format Hidden event to the
control.

ClientSideOnPopupShown(handl Function IMultiColumnDropDown Used to add the


er) name in Builder client-side
string ClientSideOnPopup
format Shown event to the
control.

ClientSideOnSelect(handler) Function IMultiColumnDropDown Used to add the


name in Builder client-side
string ClientSideOnSelect
format event to the control.

ClientSideOnTextChanged(handl Function IMultiColumnDropDown Used to add the


er) name in Builder client-side
string ClientSideOnTextCh
format anged event to the
control.

© 2014 Syncfusion. All rights reserved. 888 | Page


Essential Grid for ASP.NET MVC Classic

Events

Name Description Arguments


ClientSideOnBeforePopupShown This event is raised just get_SelectedRow() // Contains
before the popup is shown. the Selected record object
(JSON).
get_DisplayValue() // Contains
the display value.

get_SelectedValue() //
Contains the selected value.
_SelectedRow // Returns the
Selected record object
(JSON).
_DisplayValue // Returns the
display value.
_SelectedValue // Returns the
selected Value.

ClientSideOnPopupHidden This event is raised when get_SelectedRow() // Contains


the pop-up panel hides. the Selected record object
(JSON).
get_DisplayValue() // Contains
the display value.

get_SelectedValue() //
Contains the selected value.
_SelectedRow // Returns the
Selected record object
(JSON).
_DisplayValue // Returns the
display value.

_SelectedValue // Returns the


selected Value.

ClientSideOnPopupShown This event is raised when get_SelectedRow() // Contains


the pop-up panel displays. the Selected record object

© 2014 Syncfusion. All rights reserved. 889 | Page


Essential Grid for ASP.NET MVC Classic

(JSON).
get_DisplayValue() // Contains
the display value.
get_SelectedValue() //
Contains the selected value.
_SelectedRow // Returns the
Selected record object
(JSON).
_DisplayValue // Returns the
display value.
_SelectedValue // Returns the
selected Value.

ClientSideOnSelect This event is raised when get_SelectedRow() // Contains


you select the record from the Selected record object
dropdown. (JSON).
get_DisplayValue() // Contains
the display value.
get_SelectedValue() //
Contains the selected value.
_SelectedRow // Returns the
Selected record object
(JSON).
_DisplayValue // Returns the
display value.

_SelectedValue // Returns the


selected Value.

ClientSideOnTextChanged This event is raised when get_SelectedRow() // Contains


the value of the generic the Selected record object
drop-down text box (JSON).
changes.
get_DisplayValue() // Contains
the display value.
get_SelectedValue() //
Contains the selected value.
_SelectedRow // Returns the

© 2014 Syncfusion. All rights reserved. 890 | Page


Essential Grid for ASP.NET MVC Classic

Selected record object


(JSON).
_DisplayValue // Returns the
display value.
_SelectedValue // Returns the
selected Value.

4.27.3.7.1 Adding Handlers through Builder

The following code sample illustrates adding handlers through Builder.


View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
.ClientSideOnBeforePopupShown("OnBeforePopup")
.ClientSideOnPopupHidden("popupHidden")
.ClientSideOnPopupShown("popupShown")
.ClientSideOnSelect("onRecordSelect")
.ClientSideOnTextChanged("onTextChanged")
%>

View [cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AutoFormat(Skins.Office2007Black)
.Text("--Select--")
.ClientSideOnBeforePopupShown("OnBeforePopup")
.ClientSideOnPopupHidden("popupHidden")
.ClientSideOnPopupShown("popupShown")
.ClientSideOnSelect("onRecordSelect")
.ClientSideOnTextChanged("onTextChanged")
)

© 2014 Syncfusion. All rights reserved. 891 | Page


Essential Grid for ASP.NET MVC Classic

[JavaScript]

<script type="text/javascript">

function OnBeforePopup(sender, args) {


// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected
value.
// args._SelectedRow returns the selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}

function popupHidden(sender, args) {


// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected value.
// args._SelectedRow returns the selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}
function popupShown(sender, args) {
// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected value.
// args._SelectedRow returns the Selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}
function onRecordSelect(sender, args) {
// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected value.
// args._SelectedRow returns the Selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}
function onTextChanged(sender, args) {
// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.

© 2014 Syncfusion. All rights reserved. 892 | Page


Essential Grid for ASP.NET MVC Classic

// args.get_SelectedValue() contains the selected value.


// args._SelectedRow returns the Selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}
</script>

4.27.3.7.2 Adding Handlers through MultiColumnDropDownModel

Configure the MultiColumnDropDownModel as shown below to add the handlers.


// Create instance to MultiColumnDropDown model and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AutoFormat = Skins.Office2007Black,
InitiallyPopupShown=true,
ClientSideOnBeforePopupShown = "OnBeforePopup",
ClientSideOnPopupHidden = "popupHidden",
ClientSideOnPopupShown = "popupShown",
ClientSideOnSelect = "onRecordSelect",
ClientSideOnTextChanged = "onTextChanged"
};

[JavaScript]

<script type="text/javascript">

function OnBeforePopup(sender, args) {


// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected
value.
// args._SelectedRow returns the selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected Value.

© 2014 Syncfusion. All rights reserved. 893 | Page


Essential Grid for ASP.NET MVC Classic

function popupHidden(sender, args) {


// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected value.
// args._SelectedRow returns the selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}
function popupShown(sender, args) {
// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected value.
// args._SelectedRow returns the selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}
function onRecordSelect(sender, args) {
// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected value.
// args._SelectedRow returns the selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}
function onTextChanged(sender, args) {
// args.get_SelectedRow() contains the selected record
object (JSON).
// args.get_DisplayValue() contains the display value.
// args.get_SelectedValue() contains the selected value.
// args._SelectedRow returns the selected record object
(JSON).
// args._DisplayValue returns the display value.
// args._SelectedValue returns the selected value.
}
</script>

4.27.3.8 Client-Side Methods


Methods

Method Parameters Return Descriptions


type

© 2014 Syncfusion. All rights reserved. 894 | Page


Essential Grid for ASP.NET MVC Classic

setText(string) string void Sets the text to the multicolumn drop-down


text box.

getOldText() No parameter string Returns the previously displayed text.

showPopup() No parameter void Opens the pop-up panel.

hidePopup() No parameter Void Closes the pop-up panel.

Include the following code sample in the view page to set the text in a multicolumn drop-down text
box.

View[ASPX]

<input type="text" value="" id="SetDropDowntext" />


<input type="button" value="Set Text" id="setText" />

<script type="text/javascript">
$("#setText").bind('click', function () {
var multiDD = $find("MultiColumnDropdown");
multiDD.setText($('#SetDropDowntext').val());
});
</script>

Include the following code sample in the view to get the old text and show/hide the pop-up panel.

<script type="text/javascript">
$("#setText").bind('click', function () {
var multiDD = $find("MultiColumnDropdown");
multiDD.setText($('#SetDropDowntext').val());
});

function GetOldText() {
var oldText =
$find("MultiColumnDropdown").getOldText();
}
function ShowPopupPanel() {
$find("MultiColumnDropdown").showPopup();
}
function HidePopupPanel() {
$find("MultiColumnDropdown").hidePopup();
}

© 2014 Syncfusion. All rights reserved. 895 | Page


Essential Grid for ASP.NET MVC Classic

</script>

4.27.3.9 Sorting
Sorting is defined as the process of arranging items/records in some ordered sequence. Essential
Grid supports arranging table data in ascending ( ) or descending ( ) order based on the
column header that is clicked. The order switches between ascending and descending when you
click a column header for sorting.
Use Case Scenarios
Sorting is used to sort records either by ascending and descending order or by data that can be
retrieved easily.

Enabling Sorting in MultiColumnDropDown


MultiColumnDropDown supports two modes of sorting:
 Server mode
 JSON mode

4.27.3.9.1 Server Mode

Sorting in server mode can be explained in two ways:


 Builder
 MultiColumnDropDownModel

4.27.3.9.1.1 Through Builder


To sort in server mode using Builder:
1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the view, create the MultiColumnDropDown control and configure its properties.
View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>

View [cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])

© 2014 Syncfusion. All rights reserved. 896 | Page


Essential Grid for ASP.NET MVC Classic

.DisplayExpression(new int[] {2, 3, 5})


.Width(500)
.Text("--Select--")
)

3. Enable/disable the sorting feature using the AllowSorting() method.

View[Aspx]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowSorting(true)
.Text("--Select--")
%>

View [cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowSorting(true)
.Text("--Select--")
)

4. Set its data source and render the view.

Controller

/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page; it displays the
MultiColumnDropDown.</returns>
public ActionResult Index()
{

© 2014 Syncfusion. All rights reserved. 897 | Page


Essential Grid for ASP.NET MVC Classic

var Data = new


StudentDataContext().AutoFormatStudent.Take(200);
ViewData["data"] = Data;
return View(Data);
}

5. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to MultiColumnDropDown as shown in the following code.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}

6. Run the application. The MultiColumnDropDown will appear as shown in the following
screenshot.

Figure 316: Sorting Enabled MultiColumnDropDown Control

© 2014 Syncfusion. All rights reserved. 898 | Page


Essential Grid for ASP.NET MVC Classic

Figure 317: “UnivCode” Column Sorted in Descending Order

4.27.3.9.1.2 Through MultiColumnDropDownModel


To sort in server mode using MultiColumnDropDownModel:
1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. Create the MultiColumnDropDown control in the view.

View[Aspx]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))

256. Create an instance for MultiColumnDropDownModel and assign Datasource to the


model.

Controller

© 2014 Syncfusion. All rights reserved. 899 | Page


Essential Grid for ASP.NET MVC Classic

// Create instance to MultiColumnDropDownModel and assign properties.


MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500
};

257. Enable/disable the sorting feature using the AllowSorting property.

Controller

// Create instance to MultiColumnDropDownModel and assign properties.


MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AllowSorting = true
};

258. Pass the model to View using ViewData().

Controller
// Pass the MultiColumnDropDownModel to the view using ViewData()
ViewData["dropdown"] = dropdown;

259. In order to work with sorting actions, create a Post method for Index actions and bind the
data source to MultiColumnDropDown as shown in the following code sample.

Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new

© 2014 Syncfusion. All rights reserved. 900 | Page


Essential Grid for ASP.NET MVC Classic

StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}

260. Run the application. The MultiColumnDropDown control will appear as shown below.

Figure 318: Sorting Enabled MultiColumnDropDown Control

Figure 319: “UnivCode” Column Sorted by Descending Order

© 2014 Syncfusion. All rights reserved. 901 | Page


Essential Grid for ASP.NET MVC Classic

4.27.3.9.2 JSON Mode

The JSON mode of sorting renders records on the server side with all the rendering parts
processed on the client side using MicrosoftAjaxTemplate.

Sorting in JSON mode can be explained in two ways:


 Builder
 MultiColumnDropDownModel

4.27.3.9.2.1 Through Builder


To sort in JSON mode using Builder:
1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. JSON mode uses ASP.NET AJAX 4.0 Client templates for displaying the grid. Add the
MicrosoftAjax.js and MicrosoftAjaxTemplates.js files in the view as follows:

These can be downloaded from the following location:


http://ajaxcontroltoolkit.codeplex.com/releases/view/36097#DownloadId=93514

[Site.Master]
<head runat="server">
<script src="<%= Url.Content("~/Scripts/Templates/MicrosoftAjax.js")
%>" type="text/javascript"></script>
<script src="<%=
Url.Content("~/Scripts/Templates/MicrosoftAjaxTemplates.js") %>"
type="text/javascript"></script>
</head>

[_Layout.cshtml]
<head runat="server">
<script src="@Url.Content("~/Scripts/Templates/MicrosoftAjax.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/Templates/MicrosoftAjaxTemplates.js")"
type="text/javascript"></script>
</head>

© 2014 Syncfusion. All rights reserved. 902 | Page


Essential Grid for ASP.NET MVC Classic

3. Create a row template for rendering the records’ rows and setting its CSS display
property as none.

View[ASPX]
<table>
<tr id="RowTemplate" style="visibility: hidden;
display: none">
<td class="RowHeader">
</td>
<td class="RowCell">
{{OrderID}}
</td>
<td class="RowCell">
{{CustomerID}}
</td>
<td class="RowCell">
{{EmployeeID}}
</td>
<td class="RowCell">
{{ShipCountry}}
</td>
<td class="RowCell">
{{ShipCity}}
</td>
</tr>
</table>

4. In the view, create the MultiColumnDropDown control and configure its properties.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDro
pDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.Text("--Select--")
%>

View [cshtml]

@(
Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDo
wn")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})

© 2014 Syncfusion. All rights reserved. 903 | Page


Essential Grid for ASP.NET MVC Classic

.Width(500)
.Text("--Select--"))

5. Enable/disable the sorting feature using the AllowSorting() method, set the JSON mode
using ActionMode, and set the ItemTemplateID using ItemTemplate.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowSorting(true)
.ActionMode("JSON")
.ItemTemplate("RowTemplate")
.Text("--Select--")
%>

View [cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowSorting(true)
.ActionMode("JSON")
.ItemTemplate("RowTemplate")
.Text("--Select--"))

6. Set its data source and render the view.

Controller

/// <summary>
/// Used to get the JSON Order from Northwind Datacontext
/// </summary>

© 2014 Syncfusion. All rights reserved. 904 | Page


Essential Grid for ASP.NET MVC Classic

private IList<JSONOrder> Student


{
get
{
List<JSONOrder> result = (from o in new
StudentDataContext().AutoFormatStudent select new JSONOrder {
UniversityCode = o.UniversityCode, Title = o.Title, CourseFees =
o.CourseFees, CGPA = o.CGPA, ShipCountry = o.ShipCountry }).ToList();
return result;
}
}

Controller

/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page, it displays the
MultiColumnDropDown</returns>
public ActionResult Index()
{

var Data = this.Student;


ViewData["data"] = Data;
return View(Data);
}

For example, when the user tries to sort the column by clicking on the column header, the request
will be sent to the controller from the UI (view).

7. The controller gets the JSON sorting request and prepares a query for processing. The
sorting request is processed by Index HttpPost method. The required data is fetched
according to the query from the database and the response is sent to the view which is
illustrated in the following code.

Controller

/// <summary>
/// Sorting request is mapped to this method.
/// </summary>
/// <returns>JSON data is returned.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{

© 2014 Syncfusion. All rights reserved. 905 | Page


Essential Grid for ASP.NET MVC Classic

IEnumerable data = this.Orders;


var ds = this.Orders;

IOrderedEnumerable<MvcSampleApplication.Models.JSONOrder>
orderedQuery = null;
// Apply sorting to data source.
if (args.SortDescriptors != null)
{
for (int i = 0; i < args.SortDescriptors.Count;
i++)
{
var sortColumnName =
args.SortDescriptors[i].ColumnName;
if (i == 0)
{

if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Ascending)
{
orderedQuery = ds.OrderBy(c =>
c.Field(sortColumnName));
}
else if
(args.SortDescriptors[i].SortDirection ==
ListSortDirection.Descending)
{
orderedQuery = ds.OrderByDescending(c
=> c.Field(sortColumnName));
}
}
else
{
if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Ascending)
{
orderedQuery = orderedQuery.ThenBy(c
=> c.Field(sortColumnName));
}
else if
(args.SortDescriptors[i].SortDirection ==
ListSortDirection.Descending)
{
orderedQuery =
orderedQuery.ThenByDescending(c => c.Field(sortColumnName));
}
}
}
}
data = orderedQuery;

© 2014 Syncfusion. All rights reserved. 906 | Page


Essential Grid for ASP.NET MVC Classic

return Json(data);
}

8. Run the application. The MultiColumnDropDown control will appear as shown in the
following screenshot.

Figure 320: Sorting Enabled MultiColumnDropDown Control

Figure 321: “UnivCode” Column is Sorted by Descending Order

© 2014 Syncfusion. All rights reserved. 907 | Page


Essential Grid for ASP.NET MVC Classic

4.27.3.9.2.2 Through MultiColumnDropDownModel


To sort in JSON mode using MultiColumnDropDownModel:
1. Create a model in the application. Refer to How to>Adding a Model to the Application.
2. JSON mode uses ASP.NET AJAX 4.0 Client templates for displaying the Grid. Add the
MicrosoftAjax.js and MicrosoftAjaxTemplates.js files in the view as follows:

This can be downloaded from the following location:


http://ajaxcontroltoolkit.codeplex.com/releases/view/36097#DownloadId=93514

[Master Page]
<head runat="server">
<script src="<%=
Url.Content("~/Scripts/Templates/MicrosoftAjax.js") %>"
type="text/javascript"></script>
<script src="<%=
Url.Content("~/Scripts/Templates/MicrosoftAjaxTemplates.js") %>"
type="text/javascript"></script>
</head>

[_Layout.cshtml]
<head runat="server">
<script src="@Url.Content("~/Scripts/Templates/MicrosoftAjax.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~/Scripts/Templates/MicrosoftAjaxTemplates.js")"
type="text/javascript"></script>
</head>

3. Create a row template for rendering the records’ rows and set its CSS display property
as none.

View[ASPX]
<table>
<tr id="RowTemplate" style="visibility: hidden;
display: none">
<td class="RowHeader">
</td>

© 2014 Syncfusion. All rights reserved. 908 | Page


Essential Grid for ASP.NET MVC Classic

<td class="RowCell">
{{OrderID}}
</td>
<td class="RowCell">
{{CustomerID}}
</td>
<td class="RowCell">
{{EmployeeID}}
</td>
<td class="RowCell">
{{ShipCountry}}
</td>
<td class="RowCell">
{{ShipCity}}
</td>
</tr>
</table>

4. In the view, create the MultiColumnDropDown control and configure its properties.

View [ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult
iColumnDropDownModel) ViewData["dropdown"]) %>

View [cshtml]
@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(MultiCo
lumnDropDownModel) ViewData["dropdown"]))

5. Set its data source, configure the properties and render the View.

Controller
/// <summary>
/// Used to get the JSONOrder from Northwind Datacontext
/// </summary>
private IList<JSONOrder> Student
{
get
{
List<JSONOrder> result = (from o in new
StudentDataContext().AutoFormatStudent select new JSONOrder {

© 2014 Syncfusion. All rights reserved. 909 | Page


Essential Grid for ASP.NET MVC Classic

UniversityCode = o.UniversityCode, Title = o.Title, CourseFees =


o.CourseFees, CGPA = o.CGPA, ShipCountry = o.ShipCountry }).ToList();
return result;
}
}

6. Enable/disable the sorting feature using the AllowSorting() method, set the JSON mode
using ActionMode, and set the ItemTemplateID using ItemTemplate.

Controller
// Create instance to MultiColumnDropDownModel and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = this.Student;
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AllowSorting = true,
ActionMode = "JSON",
ItemTemplate = "RowTemplate"
};

For example, when the user tries to sort the column by clicking on the column header this request
will be sent to the controller from the user interface (view).
7. The controller gets the JSON sorting request, and prepares a query for processing. This
sorting request is processed by Index HttpPost method. The required data is fetched
according to the query, from the database and the response is sent to the view, which is
illustrated in the following code.
Controller

/// <summary>
///Sorting request is mapped to this method.
/// </summary>
/// <returns>JSON data is returned.</returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{

IEnumerable data = this.Orders;


var ds = this.Orders;

IOrderedEnumerable<MvcSampleApplication.Models.JSONOrder>

© 2014 Syncfusion. All rights reserved. 910 | Page


Essential Grid for ASP.NET MVC Classic

orderedQuery = null;
// Apply sorting to data source.
if (args.SortDescriptors != null)
{
for (int i = 0; i < args.SortDescriptors.Count;
i++)
{
var sortColumnName =
args.SortDescriptors[i].ColumnName;
if (i == 0)
{

if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Ascending)
{
orderedQuery = ds.OrderBy(c =>
c.Field(sortColumnName));
}
else if
(args.SortDescriptors[i].SortDirection ==
ListSortDirection.Descending)
{
orderedQuery = ds.OrderByDescending(c
=> c.Field(sortColumnName));
}
}
else
{
if (args.SortDescriptors[i].SortDirection
== ListSortDirection.Ascending)
{
orderedQuery = orderedQuery.ThenBy(c
=> c.Field(sortColumnName));
}
else if
(args.SortDescriptors[i].SortDirection ==
ListSortDirection.Descending)
{
orderedQuery =
orderedQuery.ThenByDescending(c => c.Field(sortColumnName));
}
}
}
}
data = orderedQuery;

return Json(data);
}

© 2014 Syncfusion. All rights reserved. 911 | Page


Essential Grid for ASP.NET MVC Classic

8. Run the application. The MultiColumnDropDown control will appear as shown below.

Figure 322: Sorting Enabled MultiColumnDropDown Control

Figure 323: “UnivCode” Column Sorted by Descending Order

4.27.3.9.2.3 Properties, Methods, and Events

Property Description Type Type of Value it Any other


the accepts dependencies/su

© 2014 Syncfusion. All rights reserved. 912 | Page


Essential Grid for ASP.NET MVC Classic

property b-properties
associated

AllowSorting Used to enable sorting ServerSid Boolean True/false NA


in e
MultiColumnDropDow
n

ActionMode Used to set ServerSid String JSON/Serv AllowSorting


ActionMode either e er
JSON or Server

ItemTemplat Used to set the ServerSid String Any string ActionMode


e template element ID. e

Methods

Method Arguments Return type Description

AllowSorting Boolean IMultiColumnDropDownBuilder Used to enable the


(Boolean) Sorting in
MultiColumnDropDown

ActionMode(String) String IMultiColumnDropDownBuilder Used to set


ActionMode either
JSON or Server
ItemTemplate(String) String IMultiColumnDropDownBuilder Used to set the
Template element ID.

Sample Link
To access the samples:
1. Go to Tools MVC Demos in the sample browser. Refer to Installation and Deployment >
Samples and Location.
2. Select the Multi Column Drop-Down on the left side Accordion.
3. Select any of the demos to view the full-fledged MultiColumnDropDown demo.

4.27.3.10 Filtering in the MultiColumnDropDown Control


In the MultiColumnDropDown control, the filter feature allows filtering the required set of records
and displays those filtered records in a pop-up panel.
Filtering techniques can be classified as:
 Drop-down list (basic filtering).
 Advanced filter option (as in grid MVC).

© 2014 Syncfusion. All rights reserved. 913 | Page


Essential Grid for ASP.NET MVC Classic

Drop-down list filters hold the possible values to be filtered of the particular column in the
MultiColumnDropDown control.
You can open menu and submenu items by clicking on the filter icon in the advanced filters
option.

Use Case Scenarios


 Filters are very useful when dealing with large data sets, as users can get the required
set of data when necessary.
 The user will be able to filter specific values by selecting the list box that prefixes the
desired value.
 End users can use advanced filtering options provided by submenu items from the filter
menu.

Appearance and Structure


The following figure gives you a basic idea of the structure and appearance of the filter in the
MultiColumnDropDown control.

Figure 324: Filter in the MultiColumnDropDown Control

Feature Summary
When the filter feature is enabled in the MultiColumnDropDown control, you can filter data from
multiple columns at the same time so that the data filtered is specific to your need.
Clicking the filter icon opens up a menu of fields that can be filtered out.

© 2014 Syncfusion. All rights reserved. 914 | Page


Essential Grid for ASP.NET MVC Classic

When selecting a submenu item, a separate dialog box opens and displays an advanced filter
drop-down that lists the available filter operators for the corresponding column and provides text
boxes. You can type a string to filter out whatever you require to be filtered from the table.

Where do I find Installed samples?


To view the samples:
1. Open the Syncfusion Dashboard. The Essential Studio User Interface Edition window is
displayed by default. Select ASP.NET MVC from the panel on the left side of the window.
2. Click the Run Samples button. The Essential Studio for ASP.NET MVC sample browser is
displayed.

Figure 325: Essential Tools MVC Edition Sample Browser

3. Select any sample from the Filtering tab under Multicolumn DropDown and browse
through the features.

© 2014 Syncfusion. All rights reserved. 915 | Page


Essential Grid for ASP.NET MVC Classic

Properties for Filtering in the MultiColumnDropDown Control


The properties that are used to implement filtering under the MultiColumnDropDown control are
tabulated below.

Type of Any other


Property Description Value it accepts
property dependencies

Enables the
Filtering feature.
AllowFiltering bool True/false NA
Default value is
False.

Methods
These are the methods used to implement filtering under the MultiColumnDropDown control:

Name Parameters Return type Descriptions


AllowFilter(bool) bool IMultiColumnDropDownBuilder<T> Used to enable the
Filtering in
MultiColumnDropDown

The MultiColumnDropDown control in MVC supports two modes of filtering:


 Server Mode
 JSON Mode

4.27.3.10.1 Server Mode


The filtering technique can be incorporated into the MultiColumnDropDown control in MVC by the
following two ways using the server mode:

4.27.3.10.1.1 Through Builder


View[ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("MultiColumnDropDown"
)
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowFiltering(true)
.Text("--Select--")
%>

© 2014 Syncfusion. All rights reserved. 916 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]

@(
Html.Syncfusion().MultiColumnDropDown<Student>("Multicolumndropdown")
.Datasource((IEnumerable) ViewData["data"])
.DisplayExpression(new int[] {2, 3, 5})
.Width(500)
.AllowFiltering(true)
.Text("--Select--")

))

1. Set its data source and render the View.

Controller
/// <summary>
/// Used for rendering the MultiColumnDropDown initially.
/// </summary>
/// <returns>View page; it displays
the MultiColumnDropDown.</returns>
public ActionResult Index()
{
var Data = new
StudentDataContext().AutoFormatStudent.Take(200);
ViewData["data"] = Data;
return View(Data);
}

2. In order to work with filtering actions, create a Post method for Index actions and bind the
data source to MultiColumnDropDown as in the following code:
261.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}
262.
3. Run the application. The MultiColumnDropDown control will appear as shown below:
263.

© 2014 Syncfusion. All rights reserved. 917 | Page


Essential Grid for ASP.NET MVC Classic

Figure 326: Filtering Enabled MultiColumnDropDown Control

Figure 327: “Course Fees” Column Filtered

4.27.3.10.1.2 Through MultiColumnDropDownModel


To filter in server mode using MultiColumnDropDownModel:
1. Create a model in the application
2. Create a MultiColumnDropDown control in the view.

View[ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",(Mult

© 2014 Syncfusion. All rights reserved. 918 | Page


Essential Grid for ASP.NET MVC Classic

iColumnDropDownModel) ViewData["dropdown"]) %>

View[cshtml]

@( Html.Syncfusion().MultiColumnDropDown<Student>("Multidropdown",

(MultiColumnDropDownModel) ViewData["dropdown"])))

264.
265. Create an instance for MultiColumnDropDownModel and assign Datasource to the
model.
266.
Controller
// Create instance to MultiColumnDropDownModel and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500
};

267.
268. Enable/disable the filtering feature using the AllowFiltering property.
269.
Controller
// Create instance to MultiColumnDropDownModel and assign properties.
MultiColumnDropDownModel dropdown = new
MultiColumnDropDownModel()
{
Datasource = new
StudentDataContext().JSONStudent.Skip(0).Take(30).ToList(),
Text = "--Select--",
DisplayExpression = new int[3] { 2, 3, 5 },
Width = 500,
AllowFiltering = true
};

270.
271. Pass the model to View using ViewData().

© 2014 Syncfusion. All rights reserved. 919 | Page


Essential Grid for ASP.NET MVC Classic

Controller

// Pass the MultiColumnDropDownModel to the view using ViewData()


ViewData["dropdown"] = dropdown;

272. In order to work with filtering actions, create a Post method for Index actions and bind
the data source to MultiColumnDropDown as shown in the following code.
273.
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index (PagingParams args)
{
IEnumerable data =new
StudentDataContext().AutoFormatStudent.Take(20);
return data.GridActions<Student>();
}
274.
275. Run the application. The MultiColumnDropDown control will appear as shown below:

Figure 328: Filtering Enabled MultiColumnDropDown Control

© 2014 Syncfusion. All rights reserved. 920 | Page


Essential Grid for ASP.NET MVC Classic

Figure 329: “Course Fees” Column Filtered

4.27.3.10.2 JSON Mode


The filtering technique can be incorporated into the MultiColumnDropDown control in MVC using
the Builder in the JSON mode:

4.27.3.10.2.1 Through GridBuilder


View[ASPX]

<%=Html.Syncfusion().MultiColumnDropDown<Sample.Models.Student>("MultiC
olumnDD").ActionMode(ActionMode.JSON)
.DataSource(Model)
.Columns(column=>{column.Add(p => p.Title).HeaderText("Course
Title");
column.Add(P => P.Duration).Format("{Duration} hrs");
column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
}).AllowSorting(true).DisplayExpression(new int[3]{1,3,4})
.PopupPanelWidth(700).Width(700).AllowFiltering(true)

%>

View[Razor]

@{Html.Syncfusion().MultiColumnDropDown<Sample.Models.Student>("MultiCo
lumnDD").ActionMode(ActionMode.JSON)
.DataSource(Model)
.Columns(column=>{column.Add(p => p.Title).HeaderText("Course
Title");

© 2014 Syncfusion. All rights reserved. 921 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(P => P.Duration).Format("{Duration} hrs");


column.Add(p =>
p.CourseFees).Format("{CourseFees:c}").HeaderText("Course Fees");
column.Add(p => p.CGPA);
}).AllowSorting(true).DisplayExpression(new int[3]{1,3,4})

.PopupPanelWidth(700).Width(700).AllowFiltering(true).Render();

Controller

public ActionResult index()


{
var data = new
StudentDataContext().Student.Take(200).ToList();
return View(data);
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult index(PagingParams args)
{
IEnumerable data = new
StudentDataContext().Student.Take(200).ToList();
ActionResult result = data.GridJSONActions<Student>();
return result;

Figure 330: MultiColumnDropDown Control with Filtering Enabled

© 2014 Syncfusion. All rights reserved. 922 | Page


Essential Grid for ASP.NET MVC Classic

Figure 331: Filtered with “Duration” Value as 45 hrs

4.28 Code samples


Code samples allow you to automatically insert short fragments of code into your code editor
(View). You can create and edit based on that code templates.
Syncfusion Essential Grid provides code sample support for MVC framework (MVC2, MVC3 and
MVC4) which helps you to save the time while coding.

The following steps help you to include code samples in your view:
1. Create a model in the application (Refer to: How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to: How to>Strongly Typed View).
3. Open the view and place the cursor where you would like to insert the code sample.
4. Press CTRL+K, X (or) right-click on view and select the Insert Snippet option.

Figure 332: Insert Snippet

5. Select Syncfusion ASP.NET MVC 2 (or) Syncfusion ASP.NET MVC 3 (or) Syncfusion
ASP.NET MVC 4 using the arrow keys and press enter to see a list of samples available.

© 2014 Syncfusion. All rights reserved. 923 | Page


Essential Grid for ASP.NET MVC Classic

Figure 333: Code Samples for Grid

The following table illustrates the code sample available for the Grid control for Syncfusion
ASP.NET MVC 3.

Name (or shortcut) Description Valid locations to


insert sample
#sf:gridbasic3 Creates a sample for grid with Inside View.
sorting, grouping, filtering and
paging in the aspx format.

#sf:gridbasicrazor Creates a sample for grid with Inside View.


sorting, grouping, filtering and
paging in the razor format.

#sf:gridjsonbasic3 Creates a sample for grid with Inside View.


JSON Mode, basic operations
such as sorting, grouping,
filtering and paging are enabled
in the aspx format.
#sf:gridjsonbasicrazor Creates a sample for grid with Inside View.
JSON Mode, basic operations
such as sorting, grouping,
filtering and paging are enabled
in the razor format.
#sf:gridjsonwithediting3 Creates a sample for grid with Inside View.
JSON Mode, editing and basic
operations are enabled in the
aspx format.
#sf:gridjsonwitheditingrazor Creates a sample for grid with Inside View.
JSON Mode, editing and basic
operations are enabled in the
razor format.

© 2014 Syncfusion. All rights reserved. 924 | Page


Essential Grid for ASP.NET MVC Classic

#sf:gridwithediting3 Creates a sample for grid with Inside View.


Server Mode, editing and basic
operations are enabled in the
aspx format.
#sf:gridwitheditingrazor Creates a sample for grid with Inside View.
Server Mode, editing and basic
operations are enabled in razor
format.

© 2014 Syncfusion. All rights reserved. 925 | Page


Essential Grid for ASP.NET MVC Classic

5 How to
Adding a Model to the Application

After an MVC application is created, a model has to be added. The model is a place from which
the data can be retrieved by the controller. This section guides you through the step-by-step
procedure for adding a model.

1. In the Solution Explorer, right-click the Models folder.

Note: A context menu will be displayed.

Figure 334: Context Menu Displayed when Clicking the Models Folder

2. On the context menu, point to Add and click New Item.

© 2014 Syncfusion. All rights reserved. 927 | Page


Essential Grid for ASP.NET MVC Classic

Note: The Add New Item {Application Name} is displayed. The Categories window displays the
components available under the Visual C# program. The templates window displays the templates
under the selected elements.

Figure 335: Add New Item Dialog Box


3. Click Data under Visual C#.
276.

Note: The Visual Studio installed templates are displayed in the Templates window.

© 2014 Syncfusion. All rights reserved. 928 | Page


Essential Grid for ASP.NET MVC Classic

Figure 336: Connecting a Database to the Application

Note: This step is optional and should be performed only when you want to attach a database
with the model. For details, see http://weblogs.asp.net/scottgu/archive/2007/05/29/linq-to-sql-
part-2-defining-our-data-model-classes.aspx.

4. In the Name box, type Northwind.


5. Click LINQ to SQL Classes under Templates.
6. Click Add.
277.

Note: The data classes are added under the Model folder.
7. In the Name box, enter Northwind.dbml and click the Add button.
278. Now Northwind LINQ to SQL classes are created in your application and the Object
Relational Designer appears.
8. Drag and drop the tables from the Server Explorer window onto the Object Relational
Designer to create LINQ to SQL classes that represent particular database tables. You
need to add all Northwind database tables onto the Object Relational Designer.

When you're done you will find the following screen:

© 2014 Syncfusion. All rights reserved. 929 | Page


Essential Grid for ASP.NET MVC Classic

Figure 337: Northwind.dbml

5.2 Settings for Essential Grid in MVC 4 Application


You can follow these steps to set Essential Grid in MVC 4 Application.

1. Add the following assemblies in Web.config file in the <assemblies> tag.

• Syncfusion.Core.dll

• Syncfusion.Linq.Base.dll

• Syncfusion.Shared.Mvc.dll

• Syncfusion.Theme.Base.dll

• Syncfusion.Grid.Mvc.dll

• Syncfusion.XlsIO.Mvc.dll

Refer the following code example:


<assemblies>
<add assembly="Syncfusion.Core, Version=10.304.0.43, Culture=neutral,
PublicKeyToken=632609B4D040F6B4"/>
<add assembly="Syncfusion.Shared.Mvc, Version=10.344.0.43,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Linq.Base, Version=10.304.0.43,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" />

© 2014 Syncfusion. All rights reserved. 930 | Page


Essential Grid for ASP.NET MVC Classic

<add assembly="Syncfusion.Theme.Base, Version=10.304.0.43,


Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" />
<add assembly="Syncfusion.Grid.Mvc, Version=10.344.0.43,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" />
</assemblies>

2. Add the following namespaces in the <namespaces> tag. Refer the following code example,

<namespaces>
<add namespace="Syncfusion.Grid.Mvc"/>
<add namespace="Syncfusion.Shared.Mvc"/>
</namespaces>

Note: The namespaces should also be added in the web.config file within the View folder.

3. Refer the following script files in Layout.cshtml as shown in the following code example.

<script src="@Url.Content("~/Scripts/jquery-1.7.1.min.js")"
type="text/javascript"></script>

4. The ScriptManager() method should be placed after all the components on the page. Add this
line at the end of the Layout.cshtml.

@{Html.Syncfusion().ScriptManager().Render();}

5. Suggest you to add the following handlers under the handlers tag in <system.webServer> and
httpHandlers tag in <system.web>. Refer the following code example.

<system.web>
<httpHandlers>
<add verb="GET,HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=10.344.0.43, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"
validate="false"/>
</httpHandlers>
</system.web>
<system.webServer>
<handlers>

© 2014 Syncfusion. All rights reserved. 931 | Page


Essential Grid for ASP.NET MVC Classic

<remove name="MvcResourceHandler" />


<add verb="GET,HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=10.344.0.43, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>

6. AjaxMin dll is added as reference for the purpose of Minification of Stylesheets and Scripts,
and can be copied into the precompiled assemblies folder installed with the product. Refer the
following code example:

[ASPX]

<add assembly="AjaxMin, Version=4.57.4561.28951, Culture=neutral,


PublicKeyToken=21ef50ce11b5d80f" />

5.3 Strongly Typed View


A strongly typed view is a view that defines its data model as a class instead of a weakly typed
dictionary, which could literally hold anything.
Advantages
Strongly typed views offer a number of advantages over standard views:
 You don't have to go through the laborious process of setting properties in ViewData;
values can instead be retrieved from ViewData.Model.
 IntelliSense is supported.
 Type safety is supported.
 There is no unnecessary casting between types in ViewData.
 Compile time checks can be implemented.

5.3.1 Creating a Strongly Typed View


To create a strongly typed view, six steps are involved.
1. Right-click on the View/Home folder.
2. Delete the existing Index.aspx file, making it remain as a default action.
3. Click Add, then select View.
4. Name the view Index.
5. Select Create a strongly-typed view, and in the drop-down menu select your model. In
this case it is MvcSampleApplication.Models.Order.

© 2014 Syncfusion. All rights reserved. 932 | Page


Essential Grid for ASP.NET MVC Classic

Figure 338: Creating a Strongly Typed View

Note: The View data class drop-down list will be empty until you successfully build your
application. It is a good idea to select the menu option Build to build a solution before opening the
Add New dialog.
6. In the View data class drop-down, make the model an IEnumerable collection.

© 2014 Syncfusion. All rights reserved. 933 | Page


Essential Grid for ASP.NET MVC Classic

Figure 339: Making the Model an IEnumerable Collection

5.3.2 Creating a Strongly Typed View Manually


If you create a view and later need to convert it to a strongly typed view, the process is quite
simple. Change the Inherits statement in the view declaration from:
System.Web.Mvc.ViewPage
to
System.Web.Mvc.ViewPage<YourNamespace.YourClass>
In this case, the model is MvcSampleApplication.Models.Order. So the index page should be
updated as shown below.

View
<%@ Page Language="C#" MasterPageFile="~/Views/Shared/Site.Master"
Inherits="System.Web.Mvc.ViewPage<IEnumerable<MvcSampleApplication.Mode
ls.Order>>" %>

© 2014 Syncfusion. All rights reserved. 934 | Page


Essential Grid for ASP.NET MVC Classic

Figure 340: Default Index View

Figure 341: Strongly Typed Index View

5.4 Create the ADO.NET Entity Data Model


In order to use the Entity Framework, you need to create an Entity Data Model. You can take
advantage of the Visual Studio Entity Data Model Wizard to generate an Entity Data Model from a
database automatically.
To do so, follow these six steps:
1. Right-click the Models folder in the Solution Explorer window and select the menu option
Add, New Item.
2. In the Add New Item dialog, select the Data category (see Figure 342).

© 2014 Syncfusion. All rights reserved. 935 | Page


Essential Grid for ASP.NET MVC Classic

Figure 342: Creating a New Entity Data Model

3. Select the ADO.NET Entity Data Model template, give the Entity Data Model the name
PubsDBModel.edmx, and click the Add button. Clicking the Add button launches the Data
Model Wizard.
4. In the Choose Model Contents step, choose the Generate from database option and
click the Next button (see Figure 343).

© 2014 Syncfusion. All rights reserved. 936 | Page


Essential Grid for ASP.NET MVC Classic

Figure 343: Choosing Model Contents

2. In the Choose Your Data Connection step, select the Pubs.mdf database connection,
enter the entities connection settings name PubsEntities, and click the Next button (see
Figure 344).

© 2014 Syncfusion. All rights reserved. 937 | Page


Essential Grid for ASP.NET MVC Classic

Figure 344: Choose Your Data Connection

3. In the Choose Your Database Objects step, select all the database tables and click the
Finish button (see Figure 345).

© 2014 Syncfusion. All rights reserved. 938 | Page


Essential Grid for ASP.NET MVC Classic

Figure 345: Choose Your Database Objects

When you are finished, you will be able to find the following image.

© 2014 Syncfusion. All rights reserved. 939 | Page


Essential Grid for ASP.NET MVC Classic

Figure 346: PubsDbEntity Model

5.5 Create the Generic Collection Model

1. Right-click the Models folder in the Solution Explorer window and select the menu option
Add New Item.
2. In the Add New Item window, select the Web category (see Figure 347).

© 2014 Syncfusion. All rights reserved. 940 | Page


Essential Grid for ASP.NET MVC Classic

Figure 347: Select Dialog

3. Select the Class file and give the class file name Student.cs and click the Add button.
4. Create a student class containing University Code, Course Fees, CGPA, Course ID,
Duration, and Course Title as properties.

279.
/// <summary>
/// Student class.
/// </summary>
public class Student
{
#region Properties
/// <summary>
/// Gets or sets the student name.
/// </summary>
public long UniversityCode { get; set; }

/// <summary>
/// Gets or sets the course title.
/// </summary>
public string Title { get; set; }

/// <summary>
/// Gets or sets the duration in days of the course.

© 2014 Syncfusion. All rights reserved. 941 | Page


Essential Grid for ASP.NET MVC Classic

/// </summary>
public int Duration { get; set; }

/// <summary>
/// Gets or sets course fees.
/// </summary>
public double CourseFees { get; set; }

/// <summary>
/// Gets or sets CGPA.
/// </summary>
public double CGPA { get; set; }

#endregion
}

5. Create another DataContext class to generate the students list as shown below.
280.
/// <summary>
/// StudentDataContext class.
/// </summary>
public class StudentDataContext
{
#region Properties

/// <summary>
/// Gets the courses in an IQueryable format.
/// </summary>
public List<Student> Student
{
get
{
List<Student> student = new List<Student>();
Student stu = new Student();
int code = 10000;
for (long i = 0; i < 100; i++)
{
Student[] s = new Student[10];
s[0] = new Student() { UniversityCode = code
+ 1, CourseFees = 2000.00, CGPA = 7.52, Duration = 90, Title =
"Distributed Component Architecture" };
s[1] = new Student() { UniversityCode = code
+ 2, CourseFees = 1000.00, CGPA = 9.55, Duration = 60, Title =
"Data Structures" };
s[2] = new Student() { UniversityCode = code
+ 3, CourseFees = 1750.00, CGPA = 9.03, Duration = 75, Title =
"Neural Networks" };
s[3] = new Student() { UniversityCode = code
+ 4, CourseFees = 2000.00, CGPA = 8.91, Duration = 90, Title =
"Genetic Algorithms" };

© 2014 Syncfusion. All rights reserved. 942 | Page


Essential Grid for ASP.NET MVC Classic

s[4] = new Student() { UniversityCode = code


+ 5, CourseFees = 1000.00, CGPA = 9.55, Duration = 30, Title =
"Grid Computing" };
s[5] = new Student() { UniversityCode = code
+ 6, CourseFees = 2500.00, CGPA = 9.87, Duration = 60, Title =
"Cloud Computing" };
s[6] = new Student() { UniversityCode = code
+ 7, CourseFees = 1500.00, CGPA = 9.75, Duration = 90, Title =
"Enterprise Computing" };
s[7] = new Student() { UniversityCode = code
+ 8, CourseFees = 1250.00, CGPA = 9.66, Duration = 45, Title =
"Mobile Computing" };
s[8] = new Student() { UniversityCode = code
+ 9, CourseFees = 1000.00, CGPA = 8.33, Duration = 60, Title =
"WAP and XML" };
s[9] = new Student() { UniversityCode = code
+ 10, CourseFees =1500.00, CGPA = 8.66, Duration = 75, Title =
"Design Patterns" };
foreach (Student studnt in s)
{
student.Add(studnt);
}

code += 10;
}

return student;
}
}
}

5.6 Create the Grid using view customization with


Default view

1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. In the Index view, you can use DataSource to bind the data source. Then you need to
explicitly specify the type of the data item.
View[Aspx]

<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid")

.Datasource((IEnumerable<MvcSampleApplication.Models.Order>)ViewD
ata["data"])
.EnablePaging()
.EnableSorting()
.ActionMode("Server")

© 2014 Syncfusion. All rights reserved. 943 | Page


Essential Grid for ASP.NET MVC Classic

.Column( column => {


column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
%>

3. Set its data source and render the view.


281.
Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page; it displays the grid.</returns>
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.Take(200);
return View(data);
}

4. In order to work with paging and sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code sample.

Controller

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult returns the data displayed in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();

© 2014 Syncfusion. All rights reserved. 944 | Page


Essential Grid for ASP.NET MVC Classic

5. Run the application. The grid will appear as shown below.

Figure 348: Grid with Data

5.7 How to manually configure the MVC application for


Grid
5.7.1 Creating a Platform Application

To begin, you will create a new ASP.NET MVC project.


To create a new MVC project:
1. On the File menu, click New Project. The New Project dialog box is displayed.

© 2014 Syncfusion. All rights reserved. 945 | Page


Essential Grid for ASP.NET MVC Classic

Figure 349: New Project Dialog Box

2. In the drop-down list at the top, make sure that .NET Framework 4.0 is selected.
3. In the Installed Templates panel, expand either Visual Basic or Visual C#, and then click
Web.
4. Select ASP.NET MVC 3 Web Application in the main window.
5. In the Name box, type MvcSampleApplication.
6. In the Location box, type a name for the project folder.
7. If you want the name of the solution to differ from the project name, type a name in the
Solution name box.
8. Select the Create directory for solution check box.
9. Click OK. The New ASP.NET MVC 3 Project dialog box is displayed.

© 2014 Syncfusion. All rights reserved. 946 | Page


Essential Grid for ASP.NET MVC Classic

10. Select “Internet Application” from the New ASP.NET MVC 3 Project dialog box.
11. Click OK.
282.

Note: If you want to create a unit test for your project, check the “Create a unit test project” in
the New ASP.NET MVC 3 Project dialog box and click OK.

© 2014 Syncfusion. All rights reserved. 947 | Page


Essential Grid for ASP.NET MVC Classic

The new MVC application project and a test project are generated. (If you are using the Standard
or Express editions of Visual Studio, the test project is not created.)

Examining the MVC Project


The following illustration shows the folder structure of a newly created MVC solution.

© 2014 Syncfusion. All rights reserved. 948 | Page


Essential Grid for ASP.NET MVC Classic

Figure 350: Solution Explorer

The folder structure of an MVC project differs from that of an ASP.NET Web site project. The
MVC project contains the following folders:

 Content, which is for content support files. This folder contains the cascading style sheet
(.css file) for the application.
 Controllers, which is for controller files. This folder contains the application's sample
controllers, which are named AccountController and HomeController. The
AccountController class contains login logic for the application. The HomeController
class contains logic that is called by default when the application starts.
 Models, which is for data-model files such as LINQ-to-SQL .dbml files or data-entity files.
 Scripts, which is for script files such as those that support ASP.NET AJAX and jQuery.
 Views, which is for view page files. This folder contains three subfolders: Account,
Home, and Shared. The Account folder contains views that are used as UI for logging in
and changing passwords. The Home folder contains an Index view (the default starting
page for the application) and an About page view. The Shared folder contains the
master-page view for the application.

The newly generated MVC project is a complete application that you can compile and run without
change. The following illustration shows what the application looks like when it runs in a browser.

© 2014 Syncfusion. All rights reserved. 949 | Page


Essential Grid for ASP.NET MVC Classic

Figure 351: MVC Application Output

5.7.2 Adding Essential Grid to the Application Using ASPX

Adding the Grid control to the application includes the following steps:

 Adding reference assemblies


 Adding scripts
 Adding codes to the Web.config file
 Adding resource manager
 Creating the Grid control in the view
 Passing the model from the controller to the view

5.7.2.1 Adding Reference Assemblies


1. On the Solution Explorer, right-click the References folder, and then click Add
Reference.

© 2014 Syncfusion. All rights reserved. 950 | Page


Essential Grid for ASP.NET MVC Classic

Figure 352: Add Reference Option Displayed on Right-Clicking the References Folder

Note: The Add Reference dialog box appears and the .NET tab is highlighted by default. The
assemblies for the MVC application are listed here.

© 2014 Syncfusion. All rights reserved. 951 | Page


Essential Grid for ASP.NET MVC Classic

Figure 353: Add Reference Dialog Box

1. Select the following assemblies: Syncfusion.Core, Syncfusion.Grid.Mvc,


Syncfusion.Theme.Base, Syncfusion.Linq.Base and Syncfusion.Shared.Mvc.
2. Click OK.

Note: The selected assemblies are added under References.

Figure 354: Selected Assemblies Displayed under the References Folder

The following table illustrates the MVC versions and their corresponding assembly versions.

© 2014 Syncfusion. All rights reserved. 952 | Page


Essential Grid for ASP.NET MVC Classic

MVC Assembly versions

MVC .NET Framework 3.5 .NET Framework 4.0 .NET Framework


4.5
2.0 x.x035.x.x x.x240.x.x x.x245.x.x
3.0 - x.x340.x.x x.x345.x.x
4.0 - x.x440.x.x x.x445.x.x

5.7.2.2 Adding Scripts


1. On the Solution Explorer, double-click the Views folder, double-click the Shared folder,
and then double-click the Site.Master file.

Figure 355: Site.Master File Displayed under the Shared Folder

© 2014 Syncfusion. All rights reserved. 953 | Page


Essential Grid for ASP.NET MVC Classic

Note: The Site.Master page appears.

Figure 356: Site.Master Page

2. On the Solution Explorer click the Scripts folder. The lists of available scripts are
displayed.

© 2014 Syncfusion. All rights reserved. 954 | Page


Essential Grid for ASP.NET MVC Classic

Figure 357: List of Scripts Displayed under the Scripts Folder


3. Import the following JavaScript files onto the Site.Master page.
 jquery-1.7.min.js
 MicrosoftAjax.js

[Site.Master]

<head runat="server">
…………
…………

<script src="<%= Url.Content("~/Scripts/jquery-1.7.min.js") %>"


type="text/javascript"></script>

© 2014 Syncfusion. All rights reserved. 955 | Page


Essential Grid for ASP.NET MVC Classic

<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>"


type="text/javascript"></script>

</head>

5.7.2.3 Adding Codes to the Web.config File

1. In the Solution Explorer, double-click the Web.config file. (There will be two Web.config
files. Refer to the one in the root folder.)

Note: The Web.config page appears.

Figure 358: Web.config Page

2. Add the following assemblies in the Web.config page under the <compilation> tag:
Syncfusion.Core, Syncfusion.Grid.Mvc, Syncfusion.Linq.Base and
Syncfusion.Shared.Mvc.

[Web.config]

<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>

© 2014 Syncfusion. All rights reserved. 956 | Page


Essential Grid for ASP.NET MVC Classic

…………
…………

<add assembly="Syncfusion.Core, Version=x.x040.x.x,


Culture=neutral, PublicKeyToken=632609b4d040f6b4"/>
<add assembly="Syncfusion.Theme.Base, Version=x.x040.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>

<add assembly="Syncfusion.Linq.Base, Version=x.x040.x.x,


Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Shared.Mvc, Version=x.x340.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Grid.Mvc, Version=x.x340.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
</assemblies>
</compilation>
</system.web>

3. Note: X in the above code corresponds to the correct version number of the Essential
Studio version that you are currently using.Add the Syncfusion.Mvc.Shared and
Syncfusion.Mvc.Grid namespaces under the <namespaces> tag.
283.
[web.config]

<system.web>
<pages>
<namespaces>
……….
……….
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
</namespaces>
</pages>
</system.web>

4. Register the handlers under the <httpHandlers> and <handlers> tags in the
Web.config file by using the code below.
284.
[web.config]

<system.web>
………..
………..
<httpHandlers>
<add verb="GET,HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x340.x.x, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"
validate="false"/>
</httpHandlers>
</system.web>

© 2014 Syncfusion. All rights reserved. 957 | Page


Essential Grid for ASP.NET MVC Classic

……..
<system.webServer>
…….
…….
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET,HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler,
Syncfusion.Shared.Mvc, Version=x.x340.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>

Note:

 VS2010 automatically registers all ASP.NET handlers inside the machine.config file. So add
the <httpHandlers> and <handlers> tags under <system.web> and <system.webServer>
respectively in the web.config file. For more information, refer to Clean Web.Config Files (VS
2010 and .NET 4.0 Series)

 X. in the above code corresponds to the correct version number of the Essential Studio
version that you are currently using.

5.7.2.4 Add StyleManager and ScriptManager


5.7.2.4.1 Adding StyleManager

StyleManager is a new CSS resource manager that helps in registering CSS files which enables
the minification, compression, and combination of CSS resources for ASP.NET MVC Web
applications. The files in StyleManager resources are set to be combined, minified, and
compressed (either gzip or deflate, depending on your browser) before being sent to the browser.
All are done using a single HTTP request per resource set.

Add the StyleManager extension method in the HEAD element of the view pages (in most cases,
it is reasonable to call it within the Site.Master page). Use the Register method to register the
Grid component.

View[ASPX]

<%=Html.Syncfusion().StyleManager()
.Register(styleSheet =>
{
styleSheet.Add(ComponentType.Grid);

© 2014 Syncfusion. All rights reserved. 958 | Page


Essential Grid for ASP.NET MVC Classic

}) %>

5.7.2.4.2 Adding ScriptManager


ScriptManager is a new script resource manager that helps in registering JavaScript files. The
ScriptManager registers only the Syncfusion.Mvc components script files. The files in
ScriptManager resources are set to be combined, minified, and compressed (either gzip and
deflate, depending on your browser) before sending to browser.

The ScriptManager() extension has improved performance over the RegisterStaticResource()


method, hence we always suggest this method in registering the scripts.

The ScriptManager() method should be placed after all the components on the page. Generally,
you can use this method at the end of the master page.

View[ASPX]

<body>



<%=Html.Syncfusion().ScriptManager()%>
</body>

Note: Add this ScriptManager() at the end of a <body> tag. Don’t add this in the top of a <body>
tag.

5.7.2.5 Creating the Grid control


There are two ways to add the Grid control into the MVC application:
1. Through GridBuilder
2. Through GridPropertiesModel

5.7.2.5.1 Through GridBuilder


1. Create a model in the application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file to create the Grid control in the view:

285.
View[ASPX]

<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("FlatGrid"

© 2014 Syncfusion. All rights reserved. 959 | Page


Essential Grid for ASP.NET MVC Classic

)
.Datasource(Model)
.EnablePaging()
.EnableSorting()
.Column( column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.EmployeeID).HeaderText("Employee ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
%>

Note: This is of the type: GridBuilder<T> Grid<T>(this HtmlHelper html, string id) where T: class
It is important that the ID used in the FlatGrid.aspx file and in the HomeController.cs file should
match in order to ensure binding of the properties to the control.

4. Add two methods in HomeController (one for loading the view and one for handling the
grid paging and sorting actions).

[Controller]

/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, displays the Grid</returns>
public ActionResult Index()
{
var data=new NorthwindDataContext().Orders.Take(200);
return View(data);
}

/// <summary>
/// Paging/sorting Requests are mapped to this method. This method
invokes the
/// HtmlActionResult from the grid. The required response is
generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}

© 2014 Syncfusion. All rights reserved. 960 | Page


Essential Grid for ASP.NET MVC Classic

5. Run the application.

Figure 359: Grid Control Added to the Application

5.7.2.5.2 Through GridPropertiesModel

1. Create a model into application (Refer to How to>Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.aspx file, to create the Grid control in the view:

© 2014 Syncfusion. All rights reserved. 961 | Page


Essential Grid for ASP.NET MVC Classic

View[ASPX]

<%=Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("Fla
tGrid","GridModel",
column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
%>

Note: This is of the type: string HTMLHelper.Grid<T>(string control_id, GridPropertiesModel


gridModel, Action<IRootGridColumnBuilder<T>>columns); where T: class.
It is important that the control_id used in the Index.aspx file and in the HomeController.cs file
should match to ensure the binding of the properties to the control.
4. Double-click the HomeController.cs from the Controller/Home folder. The
HomeController.cs page is displayed in the main window.

© 2014 Syncfusion. All rights reserved. 962 | Page


Essential Grid for ASP.NET MVC Classic

Figure 360: HomeController.cs Page

5. Edit the Index method as shown below:

[Controller]

/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> model = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200),

© 2014 Syncfusion. All rights reserved. 963 | Page


Essential Grid for ASP.NET MVC Classic

AllowPaging = true,
AllowSorting = true
};
ViewData["GridModel"] = model;
return View();
}

Code details:

a. Objects created for GridPropertiesModel and the following grid properties are assigned
to model
 DataSource—Gets or sets a data source for the Grid control
 AllowPaging—Gets or sets a value indicating whether the paging feature is enabled.
 AllowSorting—Gets or sets a value indicating whether the sorting feature is enabled.
b. Pass the model to view using ViewData. This will pass the grid properties from the
controller to the view.
Syntax: ViewData["model_id"] = object_name;

6. In order to work with paging/sorting actions, create a post method for Index actions and
update the following code in this method.

[Controller]

/// <summary>
/// Paging/sorting Requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}

Note: Essential Grid is fully AJAX enabled. For paging/sorting/filtering/editing actions the entire
page will not be refreshed. The grid contents alone refresh using AJAX calls. The methods above are
necessary to achieve the grid actions.

Code details:
a. Get the data source and store it in an IEnumerable collection.

© 2014 Syncfusion. All rights reserved. 964 | Page


Essential Grid for ASP.NET MVC Classic

b. Call the GridAction helper with the Type of Model, which invokes the custom action
result. This will process the data source and return the required response while calling
paging and sorting actions.
7. Run the application.

Figure 361: Grid Control Added to the Application

A sample which demonstrates a basic Grid control can be downloaded from the following link.
http://help.syncfusion.com/Support/grid_mvc/v8.3.0.20/UG/MvcGridSample.zip

Note: The version number for the assemblies has been set to 10.2.0.75 in the Web.config file of
the attached sample. Change the version number to the appropriate version in the Web.config files
(available in root directory).

5.7.3 Adding Essential Grid to the Application Using Razor


Adding the Grid control to the application includes the following steps:

© 2014 Syncfusion. All rights reserved. 965 | Page


Essential Grid for ASP.NET MVC Classic

 Adding Reference Assemblies


 Adding Scripts
 Adding Codes to the Web.config File
 Adding Resource Manager
 Creating the Grid control in the View
 Passing the model from the Controller to the View

5.7.3.1 Adding Reference Assemblies


1. On the Solution Explorer, right-click the References folder and then click Add Reference.

Figure 362: Add Reference Option Displayed on Right-Clicking the References Folder

Note: The Add Reference dialog box appears and the .NET tab is highlighted by default. The
assemblies for the MVC application are listed here.

© 2014 Syncfusion. All rights reserved. 966 | Page


Essential Grid for ASP.NET MVC Classic

Figure 363:Add Reference Dialog Box

2. Select the following assemblies: Syncfusion.Core, Syncfusion.Theme.Base,


Syncfusion.Grid.Mvc, Syncfusion.Linq.Base, and Syncfusion.Shared.Mvc.
3. Click OK.

Note: The selected assemblies are added under References.

Figure 364: Selected Assemblies Displayed under the References Folder

The following table illustrates the MVC versions and their corresponding assembly versions.

MVC Assembly versions

MVC .NET Framework 3.5 .NET Framework 4.0 .NET Framework


4.5

© 2014 Syncfusion. All rights reserved. 967 | Page


Essential Grid for ASP.NET MVC Classic

2.0 x.x235.x.x x.x240.x.x x.x245.x.x


3.0 - x.x340.x.x x.x345.x.x
4.0 - x.x440.x.x x.x445.x.x

5.7.3.2 Adding Scripts


On the Solution Explorer, double-click the Views folder, double-click the Shared folder, and
then double-click click the _Layout.cshtml file.

Figure 365: _Layout.cshtml File Displayed under the Shared Folder

Note: The _Layout.cshtml page appears.

© 2014 Syncfusion. All rights reserved. 968 | Page


Essential Grid for ASP.NET MVC Classic

Figure 366: _Layout.cshtml Page

1. On the Solution Explorer click the Scripts folder. The lists of available scripts is displayed.

© 2014 Syncfusion. All rights reserved. 969 | Page


Essential Grid for ASP.NET MVC Classic

Figure 367: List of Scripts Displayed under the Scripts Folder

286. Import the following JavaScript files onto the _Layout.cshtml page.
 jquery-1.7.min.js
 MicrosoftAjax.js

[_Layout.cshtml]

<head runat="server">
…………
…………

<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>

© 2014 Syncfusion. All rights reserved. 970 | Page


Essential Grid for ASP.NET MVC Classic

<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>

</head>

[_Layout.vbhtml]
<head runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>
</head>

5.7.3.3 Adding Codes to the Web.config File

On the Solution Explorer, double-click the Web.config file. (There will be two Web.config files.
Refer to the one in the root folder.)

© 2014 Syncfusion. All rights reserved. 971 | Page


Essential Grid for ASP.NET MVC Classic

Note: The Web.config page appears.

Figure 368: Web.config Page

Add the following assemblies in the Web.config page under the <compliation> tag:
Syncfusion.Core, Syncfusion.Grid.Mvc, Syncfusion.Linq.Base, and
Syncfusion.Shared.Mvc.
[Web.config]

<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
………….
………….
<add assembly="Syncfusion.Core, Version=x.x040.x.x,
Culture=neutral, PublicKeyToken=632609b4d040f6b4"/>
<add assembly="Syncfusion.Linq.Base, Version=x.x040.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Shared.Mvc, Version=x.x340.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Grid.Mvc, Version=x.x340.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>

© 2014 Syncfusion. All rights reserved. 972 | Page


Essential Grid for ASP.NET MVC Classic

</assemblies>
</compilation>
</system.web>

Note: X. in the above code corresponds to the correct version number of the Essential Studio
version that you are currently using.
1. Register the handlers under the <httpHandlers> and <handlers> tags in the
Web.config file by using the code below.

[Web.config]

<system.web>
………..
………..
<httpHandlers>
<add verb="GET,HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x340.x.x, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"
validate="false"/>
</httpHandlers>
</system.web>

……..
<system.webServer>
…….
…….
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET,HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler,
Syncfusion.Shared.Mvc, Version=x.x340.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>

Note: In VS2010, <httpHandlers> and <handlers> are registered inside the Machine.config file.
For more information: http://weblogs.asp.net/scottgu/archive/2009/08/25/clean-web-config-
files-vs-2010-and-net-4-0-series.aspx
Please add the <httpHandlers> and <handlers>tags under <system.web> and
<system.webServer> respectively.

© 2014 Syncfusion. All rights reserved. 973 | Page


Essential Grid for ASP.NET MVC Classic

Note: X in the above code corresponds to the correct version number of the Essential Studio
version that you are currently using.

5.7.3.4 Adding Codes to the Views Web.config file


(Views\Web.config)
(There will be two Web.config files. Refer to the one in the Views folder.)

287. Add the Syncfusion.Mvc.Shared and Syncfusion.Mvc.Grid namespaces under the


<namespaces> tag. There will be two Web.config files. Refer to the one in the Views
folder.)

[Web.config]

<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
…………..
…………..
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
</namespaces>
</pages>
</system.web.webPages.razor>

5.7.3.5 Add StyleManager and ScriptManager


5.7.3.5.1 Adding StyleManager

StyleManager is a new CSS resource manager that helps in registering CSS files which enables
the minification, compression, and combination of CSS resources for ASP.NET MVC Web
applications. The files in StyleManager resources are set to be combined, minified, and
compressed (either gzip or deflate, depending on your browser) before being sent to the browser.
All are done using a single HTTP request per resource set.

Add the StyleManager extension method in the HEAD element of the view pages (in most cases,
it is reasonable to call it within the _Layout.cshtml page). Use the Register method to register
the Grid component.

© 2014 Syncfusion. All rights reserved. 974 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]
@{Html.Syncfusion().StyleManager()
.Register(stylesheets =>
{
stylesheets.Add(ComponentType.Grid);

}).Render();}

5.7.3.5.2 Adding ScriptManager


ScriptManager is a new script resource manager that helps in registering JavaScript files. The
ScriptManager registers only the Syncfusion.Mvc component script files. The files in
ScriptManager resources are set to be combined, minified, and compressed (either gzip or
deflate, depending on your browser) before being sent to the browser.

The ScriptManager() extension has improved performance over the RegisterStaticResource()


method, hence we always suggest this method in registering the scripts.

The ScriptManager() method should be placed after all the components on the page. Generally,
you can use this method at the end of the master page.

View[cshtml]

<body>



@{Html.Syncfusion().ScriptManager().Render();}
</body>

Note: Add this ScriptManager() at the end of the <body> tag. Don’t add this in top of the <body>
tag.

5.7.3.6 Creating the Grid Control


There are two ways to create the Grid control into the MVC application.
1. Through GridBuilder
2. Through GridPropertiesModel

5.7.3.6.1 Through GridBuilder


1. Create a model into application (Refer to How to>Adding a Model to the Application)
2. Create a strongly typed view (Refer to How to>Strongly Typed View)

© 2014 Syncfusion. All rights reserved. 975 | Page


Essential Grid for ASP.NET MVC Classic

3. Add the following code in the Index.cshtml file to create the Grid control in the view:

View[cshtml]
@{ Html.Syncfusion().Grid<Sample.Models.Order>("FlatGrid")
.Datasource(Model)
.EnablePaging()
.EnableSorting()
.Column( column => {
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer ID");
column.Add(c => c.EmployeeID).HeaderText("Employee ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");
})
.Render();
}

Note: This is of the type: GridBuilder<T> Grid<T>(this HtmlHelper html, string id) where T: class
It is important that the ID used in the FlatGrid.cshtml file and in the HomeController.cs file
should match in order to ensure binding of the properties to the control.

4. Add two methods in HomeController (one for loading the view and one for handling the
grid paging/sorting actions).

[Controller]

/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, displays the Grid</returns>
public ActionResult Index()
{
var data=new NorthwindDataContext().Orders.Take(200);
return View(data);
}

/// <summary>
/// Paging/sorting requests are mapped to this method. This method
invokes the
/// HtmlActionResult from the grid. The required response is
generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)

© 2014 Syncfusion. All rights reserved. 976 | Page


Essential Grid for ASP.NET MVC Classic

{
IEnumerable data = new NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}

288. Run the application.

Figure 369: Grid Control Added to the Application

5.7.3.6.2 Through GridPropertiesModel


1. Create a model in the application (Refer to How to >Adding a Model to the Application)
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.cshtml file, to create the Grid control in the view:

© 2014 Syncfusion. All rights reserved. 977 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]

@(
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("FlatGrid","G
ridModel",
column =>{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.CustomerID).HeaderText("Customer
ID");
column.Add(c => c.EmployeeID).HeaderText("Employee
ID");
column.Add(c => c.OrderDate).HeaderText("Order
Date").Format("{OrderDate:dd/mm/yyyy}");
column.Add(c => c.Freight).HeaderText("Freight");

}))

Note: This is of the type: string HTMLHelper.Grid<T>(string control_id, GridPropertiesModel


gridModel, Action<IRootGridColumnBuilder<T>>columns); where T: class
It is important that the control_id used in the Index.cshtml file and in the HomeController.cs
file should match to ensure the binding of the properties to the control.
4. Double-click the HomeController.cs in the Controller/Home folder.
The HomeController.cs page is displayed in the main window.

© 2014 Syncfusion. All rights reserved. 978 | Page


Essential Grid for ASP.NET MVC Classic

Figure 370: HomeController.cs Page

5. Edit the Index method as like below:


[Controller]

/// <summary>
/// Used to bind the Grid.
/// </summary>
/// <returns>View page, it displays the Grid</returns>
public ActionResult Index()
{
GridPropertiesModel<Order> model = new
GridPropertiesModel<Order>()
{
DataSource = new
NorthwindDataContext().Orders.Take(200),
AllowPaging = true,
AllowSorting = true

© 2014 Syncfusion. All rights reserved. 979 | Page


Essential Grid for ASP.NET MVC Classic

};
ViewData["GridModel"] = model;
return View();
}
Code details:

a. Object created for GridPropertiesModel and the following grid properties are assigned to
model
 DataSource—Gets or sets a data source for the Grid control.
 AllowPaging—Gets or sets a value indicating whether the paging feature is enabled.
 AllowSorting—Gets or sets a value indicating whether the sorting feature is enabled.
b. Pass the model to the view using ViewData. This will pass the grid properties from the
controller to the view.
Syntax:
ViewData["model_id"] = object_name;

6. In order to work with paging and sorting actions, create a post method for Index actions and
update the following code in this method.

[Controller]

/// <summary>
/// Paging/sorting requests are mapped to this method. This
method invokes the HtmlActionResult
/// from the grid. The required response is generated.
/// </summary>
/// <param name="args">Contains paging properties </param>
/// <returns>
/// HtmlActionResult returns the data displayed on the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = new
NorthwindDataContext().Orders.Take(200);
return data.GridActions<Order>();
}

Note: Essential Grid is fully AJAX enabled. For paging/sorting/filtering/editing actions the entire
page will not be refreshed. The grid contents alone refresh using AJAX calls. The methods above are
necessary to achieve the grid actions.

Code details:
a. Get the data source and store it in a IEnumerable collection.
b. Call the GridAction helper with the Type of Model which invokes the custom action
result. This will process the data source and return the required response while calling
paging and sorting actions.

© 2014 Syncfusion. All rights reserved. 980 | Page


Essential Grid for ASP.NET MVC Classic

7. Run the application.

Figure 371: Grid Control Added to the Application

A sample which demonstrates a basic Grid control can be downloaded from the following link:
http://www.syncfusion.com/uploads/redirect.aspx?&team=support&file=MvcGridSample(Razor)13
79183234.zip

Note: The version number for the assemblies has been set to 10.2.0.75 in the Web.config file of
the attached sample. Change the version number to the appropriate version in the Web.config files
(available in root directory).

5.7.4 Adding Essential Grid to the Simple Razor Application


using VB
Adding the Grid control to the application includes the following steps:

© 2014 Syncfusion. All rights reserved. 981 | Page


Essential Grid for ASP.NET MVC Classic

 Adding Reference Assemblies.


 Adding Scripts.
 Adding Codes to the Web.config File.
 Adding a Resource Manager.
 Creating the Grid control in the View.
 Passing the model from the Controller to the View.

5.7.4.1 Adding Reference Assemblies


a. In the Solution Explorer, right-click the References folder, then click Add Reference.

Add Reference Option Displayed on Right-Clicking the References Folder

The Add Reference dialog box appears and the .NET tab is highlighted by default. The
assemblies for the MVC application are listed here.

© 2014 Syncfusion. All rights reserved. 982 | Page


Essential Grid for ASP.NET MVC Classic

a. Select the following assemblies: Syncfusion.Core, Syncfusion.Grid.Mvc,


Syncfusion.Linq.Base, Syncfusion.Theme.Base and Syncfusion.Shared.Mvc.
b. Click OK.
The selected assemblies are added under References.

5.7.4.2 Adding Scripts


a. In the Solution Explorer, double-click the Views folder, double-click the Shared folder,
and then double-click the _Layout.vbhtml file.

© 2014 Syncfusion. All rights reserved. 983 | Page


Essential Grid for ASP.NET MVC Classic

Figure 372: The _Layout.vbhtml page

b. In the Solution Explorer click the Scripts folder. The lists of scripts available are
displayed.

© 2014 Syncfusion. All rights reserved. 984 | Page


Essential Grid for ASP.NET MVC Classic

c. Import the following JavaScript files onto the _Layout.vbhtml page:


 Jquery-1.7.min.js
 MicrosoftAjax.js

[_Layout.vbhtml]
<head runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>

© 2014 Syncfusion. All rights reserved. 985 | Page


Essential Grid for ASP.NET MVC Classic

</head>

5.7.4.3 Adding Codes to the Web.config file


289.
a. In the Solution Explorer, double-click the Web.config file in the root folder.

b. Add the following assemblies in the Web.config page under the <compilation> tag:

 Syncfusion.Core
 Syncfusion.Grid.Mvc
 Syncfusion.Linq.Base
 Syncfusion.Theme.Base
 Syncfusion.Shared.Mvc

© 2014 Syncfusion. All rights reserved. 986 | Page


Essential Grid for ASP.NET MVC Classic

[Web.config]
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Syncfusion.Core, Version=x.x040.x.xx,
Culture=neutral, PublicKeyToken=632609b4d040f6b4"/>
<add assembly="Syncfusion.Linq.Base, Version= x.x040.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Shared.Mvc, Version= x.x340.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Grid.Mvc, Version= x.x340.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Theme.Base, Version= x.x340.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" />
</assemblies>
</compilation>

Register the handlers under the <httpHandlers> and <handlers> tags in the Web.config file
by using the code below.

[Web.config]
<system.web>
<httpHandlers>
<add verb="GET, HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version= x.x340.x.xx, Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"
validate="false"/>
</httpHandlers>
</system.web>

<system.webServer>
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET, HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version= x.x340.x.xx, Culture=neutral,

© 2014 Syncfusion. All rights reserved. 987 | Page


Essential Grid for ASP.NET MVC Classic

PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>

Note: X. in the above code corresponds to the correct version number of the Essential Studio
version that you are currently using.

5.7.4.4 Adding Codes to the Views Web.config file


(Views\Web.config)
Note: There are two Web.config files. Refer to the one in the Views folder.

a. Add the following namespaces under the <namespaces> tag:


 Syncfusion.Mvc.Shared
 Syncfusion.Mvc.Grid

[Web.config]
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
</namespaces>
</pages>
</system.web.webPages.razor>

290. Adding StyleManager


Add the StyleManager extension method in the HEAD element of the view pages (in most cases,
it is reasonable to call it within the _Layout.vbhtml page).

[vbhtml]

View[Razor]
@Code
Dim styleManager =

© 2014 Syncfusion. All rights reserved. 988 | Page


Essential Grid for ASP.NET MVC Classic

Html.Syncfusion.StyleManager.Register(Function(register)
register.Add("~/Content/Site.css")) 'Register CSS files.
styleManager.Register(Function(register)
register.Add(ComponentType.Grid)) 'Register controls.
'Render the style manager.
styleManager.Render()
End Code

5.7.4.5 Add StyleManager and ScriptManager


5.7.4.5.1 Adding StyleManager

StyleManager is a new CSS resource manager that helps in registering CSS files which enables
the minification, compression, and combination of CSS resources for ASP.NET MVC Web
applications. The files in StyleManager resources are set to be combined, minified, and
compressed (either gzip or deflate, depending on your browser) before being sent to the browser.
All are done using a single HTTP request per resource set.
Add the StyleManager extension method in the HEAD element of the view pages (in most cases,
it is reasonable to call it within the _Layout.vbhtml page). Use the Register method to register
the Grid component.
Razor[vbhtml]
@code
Dim styleManager = Html.Syncfusion.StyleManager
styleManager.Register(Function(register)
register.Add("~/Content/Site.css"))
styleManager.Register(Function(register)
register.Add(ComponentType.Grid))

'render the style manager


styleManager.Render()
styleManager.Minify = true
styleManager.Combine = true
End Code

5.7.4.5.2 Adding ScriptManager


ScriptManager is a new script resource manager that helps in registering JavaScript files. The
ScriptManager registers only the Syncfusion.Mvc component script files. The files in
ScriptManager resources are set to be combined, minified, and compressed (either gzip or
deflate, depending on your browser) before being sent to the browser.

The ScriptManager() extension has improved performance over the RegisterStaticResource()


method, hence we always suggest this method in registering the scripts.

© 2014 Syncfusion. All rights reserved. 989 | Page


Essential Grid for ASP.NET MVC Classic

The ScriptManager() method should be placed after all the components on the page. Generally,
you can use this method at the end of the master page.

Razor[vbhtml]

<body>



@code
Html.Syncfusion().ScriptManager().Combine(true).Minify(true).Render()
End Code
</body>

Note: Add this ScriptManager() at the end of the <body> tag. Don’t add this in top of the <body>
tag.

5.7.4.6 Creating the Grid Control in the View


291.
1. Create the database in the application.
2. Create a model in the application(refer to How to > Adding a Model to the Application).
3. Create a strongly typed view(refer to How to > Creating a Strongly Typed View).
4. Add the following code in the Index.vbhtml file to create the Grid control in the view:
[vbhtml]

[Razor]
@Code
Dim gridbuilder = Html.Syncfusion().Grid(Of
GridSample.Order)("SampleGrid").Datasource(Model)

'Add grid columns using gridbuilder.


gridbuilder.Column(Function(cols) cols.Add(Of Integer)(Function(c
As GridSample.Order) c.OrderID).HeaderText("OrderID"))
gridbuilder.Column(Function(cols) cols.Add(Of Integer)(Function(c
As GridSample.Order) c.EmployeeID).HeaderText("EmployeeID"))
gridbuilder.Column(Function(cols) cols.Add(Of Integer)(Function(c
As GridSample.Order) c.CustomerID).HeaderText("CustomerID"))
gridbuilder.Column(Function(cols) cols.Add(Of Short)(Function(c As
GridSample.Order) c.ShipCountry).HeaderText("ShipCountry"))
gridbuilder.Column(Function(cols) cols.Add(Of Date)(Function(c As

© 2014 Syncfusion. All rights reserved. 990 | Page


Essential Grid for ASP.NET MVC Classic

GridSample.Order)
c.OrderDate).HeaderText("OrderDate").Format("{OrderDate:dd/MM/yyyy}"))

gridbuilder.EnablePaging()
gridbuilder.EnableGrouping()
gridbuilder.EnableSorting()
gridbuilder.Render()

End Code

5. Add two methods in HomeController (one for loading the view and one for handling the
grid paging and sorting actions)

[vbhtml]

Controller

Public Class HomeController


Inherits System.Web.Mvc.Controller

Public Function Index() As ActionResult


Dim data = New NorthwindDataContext().Orders.ToList()
Return View(data)
End Function

<AcceptVerbs(HttpVerbs.Post)> _
Public Function Index(ByVal args As PagingParams) As
ActionResult

Dim data As IEnumerable = New


NorthwindDataContext().Orders.ToList()
Return data.GridActions(Of Order)()
End Function
End Class

© 2014 Syncfusion. All rights reserved. 991 | Page


Essential Grid for ASP.NET MVC Classic

6. Run the application. The output will be as follows:

5.7.5 Elaborate Structure of the Control


The following illustration shows the structure of the Grid control:

© 2014 Syncfusion. All rights reserved. 992 | Page


Essential Grid for ASP.NET MVC Classic

Figure 373: Structure of Grid Control

5.7.5.1 Elements and Features

 Grouping—This process enables categorization of records based on specific columns.


You can easily group records based on a particular column by dragging the column to the
upper portion of the grid.
 Sorting—This process enables arrangemen of items/records in ordered sequence.
 Editing—This process allows you to edit, add, and delete grid records.
 Filtering—This process allows you to extract a subset of records based on certain filter
criteria.
 Resizing—The grid allows you to resize the width of the columns.
 Drag-and-Drop Support—Support to reposition columns by dragging the respective
column headers.
 Pager Bar—The pager bar available at the bottom of a grid facilitates splitting up huge
grid data and displays a viewable set of Grid rows with numbering in each page. By
selecting the respective page numbers, you can navigate to the other pages.
 Group Drop Area—The header cell of a particular column can be dragged onto the group
drop area to group the table by the respective columns.

5.7.6 Feature Summary

This section will walk you through all the features of the Grid control.

© 2014 Syncfusion. All rights reserved. 993 | Page


Essential Grid for ASP.NET MVC Classic

5.7.6.1 Appearance

Essential Grid has several built-in skins that make styling extremely easy. It is also possible to
easily format the data displayed in the grid.

Essential Grid for ASP.NET MVC contains 14 built-in skins to easily customize appearance.
Essential Grid's AutoFormat property allows you to apply predefined skins to the control. Some
of the available skins are illustrated in detail in the Built-in Skin Styles section.

Figure 374: Grid Themes

5.7.6.2 Grouping
Essential Grid has built-in capability to group data by one or more columns. Grouping is done on
the server and the required data is only sent back to the client by using AJAX, so the operation is
greatly optimized for speed and data transfer. The records displayed in the grid can be grouped
by one or more columns.

© 2014 Syncfusion. All rights reserved. 994 | Page


Essential Grid for ASP.NET MVC Classic

Grouping operations can be done programmatically or can be initiated by you. You can simply
drag and drop the desired column header to a group drop area located at the top of the grid to
group by a particular column. Refer to the Grouping topic to know more.

Figure 375: Grid Data Grouped By Employee ID

5.7.6.3 Sorting
Essential Grid has built-in support for sorting by one or more columns. It is also possible to sort
by using custom logic.

a. Sorting columns
The default grid settings allow the grid data to be sorted in ascending or descending
order by the selected column.
b. Multicolumn sorting
The default grid settings allow multiple columns to be sorted by clicking the desired
column headers while holding CTRL. There are also options for clearing the sort and
disabling sorting on a specific column. For more information about this feature, see
Sorting.

© 2014 Syncfusion. All rights reserved. 995 | Page


Essential Grid for ASP.NET MVC Classic

Figure 376: Sorted Grid Columns


c. JSON mode sorting
The JSON mode of sorting provides an efficient way to retrieve sorted data as JSON
objects. The advantage of this approach is that only data is updated and the client-side
grid refreshes itself to display the updated data. This is AJAX at its best.

5.7.6.4 Filtering
Essential Grid allows you to filter data in the control using the Filter menu. See Filtering.

Figure 377: Filter Menu

5.7.6.5 Paging
Essential Grid includes a pager bar that can be used to easily navigate to the required page when
the grid has data that spans several pages. See Paging.

a. Pager bar

© 2014 Syncfusion. All rights reserved. 996 | Page


Essential Grid for ASP.NET MVC Classic

Essential Grid for ASP.NET MVC includes a pager bar that can be used to navigate to a
specific page. There are also options to control the number of pages displayed.

Figure 378: Multi-Page Grid

b. JSON mode paging


The JSON mode of paging provides an efficient way to retrieve paged data as JSON
objects. The advantage of this approach is that only data is refreshed and the client-side
grid refreshes itself to display the updated data. This results in vastly improved scalability.

5.7.6.6 Editing
Essential Grid provides built-in support inserting, updating, and deleting records inside the grid.
The grid provides three types of editing modes. See Editing.

 Normal edit mode


 Inline form edit mode
 Inline template form edit mode

© 2014 Syncfusion. All rights reserved. 997 | Page


Essential Grid for ASP.NET MVC Classic

Figure 379: Inline Row Editing

© 2014 Syncfusion. All rights reserved. 998 | Page


Essential Grid for ASP.NET MVC Classic

Figure 380: Inline Form Editing

© 2014 Syncfusion. All rights reserved. 999 | Page


Essential Grid for ASP.NET MVC Classic

Figure 381: Inline Template Form Editing

5.7.6.7 Exporting

The Grid control has built-in support for exporting a grid to Excel. You can download data from
the Grid control to an Excel worksheet for offline verification and/or computation. This can be
achieved by using the GridExcelExportActionResult<T> extension. See Exporting.

© 2014 Syncfusion. All rights reserved. 1000 | Page


Essential Grid for ASP.NET MVC Classic

Figure 382: Exported Grid Content

5.7.6.8 Summaries
You can easily create summaries for grid records using summary row descriptor collections. Pre-
built summary types include sum, average, and summary. See Summaries.

© 2014 Syncfusion. All rights reserved. 1001 | Page


Essential Grid for ASP.NET MVC Classic

Figure 383: Grid Summary

5.7.6.9 Scrolling
Specify a width and height for the control and the grid will automatically show scroll bars if
necessary. See Scrolling.

Figure 384: Grid with Scroll Bar

5.7.6.10 Formatting Data


Essential Grid provides multiple options to format the data displayed in the grid. For more
information refer to Formatting.
a. Column formatting

© 2014 Syncfusion. All rights reserved. 1002 | Page


Essential Grid for ASP.NET MVC Classic

Essential Grid uses the Format() and CssClass() methods to format columns.

Figure 385: Column Formatting for Bound Columns

Figure 386: Column Formatting for Unbound Column Using Format()

© 2014 Syncfusion. All rights reserved. 1003 | Page


Essential Grid for ASP.NET MVC Classic

Figure 387: Column Formatting Using CssClass()


b. Custom formatting
Essential Grid provides support for formatting cells and rows at run time by using the
QueryCellInfo() and RowDataBound() events.

Figure 388: Grid Formatted Using QueryCellInfo()

© 2014 Syncfusion. All rights reserved. 1004 | Page


Essential Grid for ASP.NET MVC Classic

Figure 389: Grid Formatted Using RowDataBound() Event

Conditional formatting
Essential Grid has built-in support for conditional formatting. This feature allows you to format the
grid cells based on a certain condition. This can be achieved by defining a
GridConditionalFormatDescriptor<T> for the grid.

Figure 390: Grid Formatted Using ConditionalFormat

© 2014 Syncfusion. All rights reserved. 1005 | Page


Essential Grid for ASP.NET MVC Classic

5.7.6.11 Unbound Column Support

Essential Grid supports the addition of unbound columns in the grid. Please refer to the Unbound
Column section.

Figure 391: Unbound Columns

5.7.6.12 Drag-and-Drop Support

Essential Grid provides support for dragging and dropping records between grids and HTML
elements. See Drag and Drop.

Figure 392: Dragging and Dropping Records

5.7.6.13 Client-Side Interactivity

© 2014 Syncfusion. All rights reserved. 1006 | Page


Essential Grid for ASP.NET MVC Classic

Essential Grid has several client-side interactions to enhance the end-user experience. See
Client-Side Events and Methods.
a. Selection
Essential Grid has client-side interaction options to select a single row, a group or rows or the
whole grid. For details, see Selection.

Figure 393: Selecting a Column

b. Column resizing
Essential Grid's column widths can be interactively adjusted by dragging and resizing the
desired columns.

© 2014 Syncfusion. All rights reserved. 1007 | Page


Essential Grid for ASP.NET MVC Classic

Figure 394: Column Resizing

c. Drag-and-drop support:
Essential Grid's column positions can be re-arranged by dragging a desired column
header to a new location. Cue arrows provide hints about the destination location.

Figure 395: Column Drag-and-Drop

© 2014 Syncfusion. All rights reserved. 1008 | Page


Essential Grid for ASP.NET MVC Classic

5.8 How do I Add Essential Grid to the Simple MVC 4


Razor Application?

5.8.1 Adding reference assemblies


1. In the Solution Explorer, right-click the References folder and then click Add Reference.

The Add Reference dialog box appears and the .NET tab is highlighted by default. The
assemblies for the MVC application are listed in the dialog box.

© 2014 Syncfusion. All rights reserved. 1009 | Page


Essential Grid for ASP.NET MVC Classic

2. Select the following assemblies:

 Syncfusion.Core
 Syncfusion.Linq.Base
 Syncfusion.Theme.Base
 Syncfusion.Grid.Mvc
 Syncfusion.Shared.Mvc

3. Click OK.

The selected assemblies are added under the References folder.

© 2014 Syncfusion. All rights reserved. 1010 | Page


Essential Grid for ASP.NET MVC Classic

5.8.2 Adding Scripts


1. In the Solution Explorer, double-click the Views folder, then double-click
the Shared folder, and then double-click the _Layout.cshtml file.

The _Layout.cshtml page appears.

© 2014 Syncfusion. All rights reserved. 1011 | Page


Essential Grid for ASP.NET MVC Classic

Figure330: The _Layout.cshtml Page

2. In the Solution Explorer, click the Scripts folder. The list of scripts available is
displayed.

© 2014 Syncfusion. All rights reserved. 1012 | Page


Essential Grid for ASP.NET MVC Classic

Import the following JavaScript files onto the _Layout.cshtml page.


 jquery-1.7.min.js
 MicrosoftAjax.js
[_Layout.cshtml]

<head runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js")"
type="text/javascript"></script>
</head>

© 2014 Syncfusion. All rights reserved. 1013 | Page


Essential Grid for ASP.NET MVC Classic

5.8.3 Configure the root Web.config file

1. In the Solution Explorer, double-click the Web.config file in the root folder.

2. Add the following assemblies in the Web.config page under the <compilation> tag:
 Syncfusion.Core
 Syncfusion.Grid.Mvc
 Syncfusion.Shared.Mvc
 Syncfusion.Linq.Base
 Syncfusion.Theme.Base

© 2014 Syncfusion. All rights reserved. 1014 | Page


Essential Grid for ASP.NET MVC Classic

[Web.config]
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Syncfusion.Core, Version=X.X045.X.X,
Culture=neutral, PublicKeyToken=632609b4d040f6b4"/>
<add assembly="Syncfusion.Linq.Base, Version=X.X045.X.X,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Theme.Base, Version=X.X045.X.X,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Grid.Mvc, Version=X.X445.X.X,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Shared.Mvc, Version=X.X445.X.X,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
</assemblies>
</compilation>

Note: X in the above code corresponds to the version number of Essential Studio that you are
currently using.
3. Register the handlers under the <httpHandlers> and <handlers> tags in
the Web.config file by using the code below.

[Web.config]
<system.web>
<httpHandlers>
<add verb="GET,
HEAD" path="MvcResourceHandler.axd"type="Syncfusion.Mvc.Shared.MvcResou
rceHandler, Syncfusion.Shared.Mvc, Version=x.x445.x.xx,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"validate="false"/>
</httpHandlers>
</system.web>

<system.webServer>
<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET,
HEAD" name="MvcResourceHandler"path="MvcResourceHandler.axd" type="Sync
fusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x445.x.xx, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>

© 2014 Syncfusion. All rights reserved. 1015 | Page


Essential Grid for ASP.NET MVC Classic

</system.webServer>

5.8.4 Configuring the Views Web.config (Views\Web.config)


Note: There are two Web.config files. Refer to the one in the Views folder.

1. Add the following namespaces under the <namespaces> tag.

 Syncfusion.Mvc.Grid
 Syncfusion.Mvc.Shared

[Web.config]
<system.web.webPages.razor>
<pages pageBaseType="System.Web.Mvc.WebViewPage">
<namespaces>
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
</namespaces>
</pages>
</system.web.webPages.razor>

5.8.5 Adding StyleManager

Add the StyleManager extension method in the head element of the view pages (in most cases,
it is reasonable to call it within the _Layout.cshtml ).
[cshtml]
@{Html.Syncfusion().StyleManager()

.Register(stylesheets =>
{
stylesheets.Add(ComponentType.Grid);

}).Render();}

© 2014 Syncfusion. All rights reserved. 1016 | Page


Essential Grid for ASP.NET MVC Classic

5.8.6 Adding ScriptManager

The ScriptManager() method should be placed after all of the components on the page.
Generally, this method can be used at the end of the Layout.cshtml page.

[Razor]
<body>
. . .
@{Html.Syncfusion().ScriptManager().Render();}
</body>

Note: Add this ScriptManager() at the end of <body> tag. Don’t add this in the top of
the <body> tag.

5.8.7 Creating the Grid Control in the View

1. Create the database in the application.


2. Create a model in the application(refer to How to > Adding a Model to the Application).
3. Create a strongly typed view (refer to How to > Strongly typed view).
4. Add the following code in the Index.cshtml file to create the Grid control in the view:

[Razor]
@model IEnumerable<MvcSampleApplication.Models.Order>

@{
Html.Syncfusion().Grid<MvcSampleApplication.Models.Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.CustomerID);
col.Add(c => c.OrderDate);
col.Add(c => c.ShipCountry);
col.Add(c => c.Freight);
})

© 2014 Syncfusion. All rights reserved. 1017 | Page


Essential Grid for ASP.NET MVC Classic

.EnablePaging()
.EnableSorting()
.EnableGrouping()
.EnableFiltering()
.Render();
}

5. Add two methods in the HomeController (one for loading the view and one for handling
the grid
paging and sorting actions).

Controller

/// <summary>
/// Used to bind the grid.
/// </summary>
/// <returns>View page, displays the grid.</returns>

public ActionResult Index()


{
var data = new NorthwindDataContext().Orders.ToList();
return View(data);
}

/// <summary>
/// Paging and sorting requests are mapped to this method. This
/// method invokes the HtmlActionResult from the grid. The
required
/// response is generated.
/// </summary>
/// <param name="args">Contains paging properties.</param>
/// <returns>
/// HtmlActionResult, returns the data displayed in the grid.
/// </returns>
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{

IEnumerable data
= new NorthwindDataContext().Orders.ToList();
return data.GridActions<Order>();

© 2014 Syncfusion. All rights reserved. 1018 | Page


Essential Grid for ASP.NET MVC Classic

6. Run the application. The output will be as follows:

5.9 How to avoid Grid Invisibility

The following are the steps to avoid Grid invisibility:


1. Add script manager
Place the ScriptManager () method after all the components on the page.
Using ASPX code
You can use this method at the end of the Site.Master page in general as given in the following
code:
<body>
….
<%=Html.Syncfusion().ScriptManager() %>
</body>

Using Razor code


You can use this method at the end of the Layout.cshtml page in general as given in the following
code:

© 2014 Syncfusion. All rights reserved. 1019 | Page


Essential Grid for ASP.NET MVC Classic

<body>
….
@{Html.Syncfusion().ScriptManager().Render();}
</body>

2. Add scripts
Add the necessary script file.
Using ASPX code
Place the scripts in the Site.Master page as given in the following code:

<head id="Head1" runat="server">


<script src="<%= Url.Content("~/Scripts/jquery-1.7.min.js") %>"
type="text/javascript"></script>
<script src="<%= Url.Content("~/Scripts/MicrosoftAjax.js") %>"
type="text/javascript"></script>
<script src="<%=Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")%>"
type="text/javascript"></script>
</head>

Using Razor code


Place the scripts in Layout.cshtml page as given in the following code:

<head runat="server">
<script src="@Url.Content("~/Scripts/jquery-1.7.min.js")"
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftAjax.js") "
type="text/javascript"></script>
<script src="@Url.Content("~/Scripts/MicrosoftMvcValidation.debug.js")"
type="text/javascript"></script>
</head>

3. Add the Syncfusion.Grid.Mvc assembly to the web.config file.


The following code illustrates how to add the assembly and namespace:
[Web.config]
<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Syncfusion.Grid.Mvc, Version=x.x340.x.x,
Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Core, Version=x.x040.x.x, Culture=neutral,
PublicKeyToken=632609B4D040F6B4"/>
<add assembly="Syncfusion.Shared.Mvc, Version=x.x340.x.x,

© 2014 Syncfusion. All rights reserved. 1020 | Page


Essential Grid for ASP.NET MVC Classic

Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>
<add assembly="Syncfusion.Linq.Base, Version=x.x040.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89" />
<add assembly="Syncfusion.Theme.Base, Version=x.x040.x.x,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89" />
.. .
. . .
</compilation>
...
</system.web>

4. Add the namespaces to the web.config file.


For the Razor engine, place the namespace in Views > web.config.

Note: There will be two web.config files. Place the namespace in the web.config file in the Views
folder.

For ASPX engine place the namespace in Root > web.config file.

<pages>
<namespaces>
. . .
<add namespace="Syncfusion.Mvc.Shared"/>
<add namespace="Syncfusion.Mvc.Grid"/>
. . .
</namespaces>
</pages>

5. Register the handlers under <httphandlers>, <handlers> tags in the web.config file
The following code illustrates this:

<system.web>
<httpHandlers>
<add verb="GET, HEAD" path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x340.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89" validate="false"/>
</httpHandlers>
</system.web>

<system.webServer>

© 2014 Syncfusion. All rights reserved. 1021 | Page


Essential Grid for ASP.NET MVC Classic

<handlers>
<remove name="MvcResourceHandler"/>
<add verb="GET, HEAD" name="MvcResourceHandler"
path="MvcResourceHandler.axd"
type="Syncfusion.Mvc.Shared.MvcResourceHandler, Syncfusion.Shared.Mvc,
Version=x.x340.x.x, Culture=neutral,
PublicKeyToken=3d67ed1f87d44c89"/>
</handlers>
</system.webServer>

Using AJAX to Load Grid


Follow the below steps while using AJAX to load grid:
1. While using Ajax post scripts will not be evaluated. To overcome this use
$.fn.sfEvalScripts(data) function.
The following code illustrates this:
[Script]

$.ajax({
type: 'post',
url: "Home/JQueryAjaxAction",
datatype: 'html',
success: function (data) {
$("#JQueryAjaxLoadingSyncfusionGrid")[0].innerHTML = data;
$.fn.sfEvalScripts(data);
}
});

292. Grid Invisibility Issue may occur, when using Ajax.BeginForm. To avoid this issue, use
the Ajax.BeginFormExt instead. The following code illustrates this:

[ASPX]

<%using (Ajax.BeginFormExt("AjaxFormAction", new AjaxOptions() {


UpdateTargetId = "AjaxFormLoadingSyncfusionGrid" }))
{%>
<%=
Html.Syncfusion().Button("GridLoadusingBeginFormExt").Type(ButtonTypes.Submi
t).Text("Grid Load using BeginFormExt") %></div>
<%} %>

© 2014 Syncfusion. All rights reserved. 1022 | Page


Essential Grid for ASP.NET MVC Classic

[Razor]

@{ using (Ajax.BeginFormExt("AjaxFormAction", new AjaxOptions() {


UpdateTargetId = "AjaxFormLoadingSyncfusionGrid" }))
{
@(
Html.Syncfusion().Button("GridLoadusingBeginFormExt").Type(ButtonTypes.Submi
t).Text("Grid Load using BeginFormExt"))
}
}

5.10 How to Use Other Controls Inside the


DialogEditorTemplate?
Essential Grid allows you to use other controls inside the DialogEditorTemplate. You need to
make a note on the setting of z-index property for the control while using the controls inside the
DialogEditorTemplate. In some cases, the control may set behind the Dialog. To make the control
visible, you have to set the z-index for the control using their appropriate CSS classes. For
example, when using the UploadBox and AutoCompleteTextBox controls inside the
DialogEditorTemplate, you have to set the z-index as illustrated in the following code examples.

[C#]

// For UploadBox
.uploadbox .sf_uploadinput
{
z-index: 9999 !important;
}

[C#]

// For AutoCompleteTextBox
.Autocomplete_SuggestionList
{
z-index: 9999 !important;
}

5.11 How to create and assign columns to a grid in the


controller through the grid-properties model

Columns are defined in the view page. For defining columns in the controller, the grid properties
model is used.
Here the column property of the GridPropertyModel is used to define the columns.

© 2014 Syncfusion. All rights reserved. 1023 | Page


Essential Grid for ASP.NET MVC Classic

1. Create a model in the application (refer to How to > Adding a Model to the Application).
2. Create a strongly typed view (Refer to How to>Strongly Typed View).
3. Add the following code in the Index.cshtml file to create the Grid control in the view.
View [cshtml]
@( Html.Syncfusion().Grid<Editing.Models.EditableOrder>("Orders_Grid",

(GridPropertiesModel<Editing.Models.EditableOrder>)ViewData["GridModel"]))

4. Create a GridPropertiesModel in the Index method. Assign columns to the grid using
the columns property in this model and set other properties of the model, then pass the
model from controller to view using the ViewData class as shown below:
/// <summary>
/// Used for rendering the grid initially.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
/// <summary>
/// Used for rendering the grid initially.
/// Columns are defined in GridPropertiesModel.
/// </summary>
/// <returns>View page, it displays the grid.</returns>
public ActionResult Index()
{
var model = new GridPropertiesModel<EditableOrder>
{
Caption = "Order",
AllowPaging = true,
AllowSorting = true,
Filters = new GridFiltering
{
AllowFiltering = true,
FilterMode = FilterMode.Default,
},
AutoFormat = Skins. Office2007Blue,
Height = 500,
DataSource = OrderRepository.GetAllRecords()
};
model.Columns = new List<GridColumn<EditableOrder>>
{
new GridColumn<EditableOrder>
{
HeaderText = "Order ID",
MappingName = "OrderID",
ColumnType=typeof(int)
},
new GridColumn<EditableOrder>
{
HeaderText = "Customer ID",

© 2014 Syncfusion. All rights reserved. 1024 | Page


Essential Grid for ASP.NET MVC Classic

MappingName = "CustomerID",
ColumnType=typeof(string)
},
new GridColumn<EditableOrder>
{
HeaderText = "Employee ID",
MappingName = "EmployeeID",
ColumnType=typeof(int)
},
new GridColumn<EditableOrder>
{
HeaderText = "Order Date",
MappingName = "OrderDate",
Format =
"{OrderDate:MM/dd/yyyy}",

ColumnType=typeof(DateTime?)
},
new GridColumn<EditableOrder>
{
HeaderText = "Freight",
MappingName = "Freight",
ColumnType=typeof(decimal)
},
};
ViewData["GridModel"] = model;
return View();
}

5. In order to work with paging or sorting actions, create a Post method for Index actions
and bind the data source to the grid as shown in the following code:
Controller

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();

6. Run the application. The grid will appear as shown below.

© 2014 Syncfusion. All rights reserved. 1025 | Page


Essential Grid for ASP.NET MVC Classic

5.12 How to: overcome “Registering style sheet for the


Grid failed because assembly does not exist” error

You can follow these steps to overcome this “Registering style sheet for the Grid failed because
assembly does not exist” error,

1. Add the following reference assembly to the project:

 Syncfusion.Theme.Base

2. Add the following assembly to the Web.config page under the <compilation> tag.

 Syncfusion.Theme.Base

The following code example shows how to add this assembly in Web.config page:

[Web.config]

<system.web>
<compilation debug="true" targetFramework="4.0">
<assemblies>
<add assembly="Syncfusion.Theme.Base, Version=10.404.0.53,
Culture=neutral, PublicKeyToken=3d67ed1f87d44c89"/>

© 2014 Syncfusion. All rights reserved. 1026 | Page


Essential Grid for ASP.NET MVC Classic

</assemblies>
</system.web>

5.13 How to: Resolve Database configuration error


The Database configuration error “Cannot connect to the configuration database” is based on
database instance which can be resolved in two ways as follows:

Option 1:

You can follow these steps to resolve Database configuration error:

1. Click explore sample in Dashboard and open the Grid samples project.

2. Check the connection string instance in Web.config file. The current database instance can be
found using VS2010 as follows.

[Tools] -> [Options] -> [Database Tools] -> [Data Connections] - "Sql Server Instance Name
(blank for default):"

For example:

“Data Source=.\SQLEXPRESS”

<add name="NORTHWNDConnectionString" connectionString="Data


Source=.\SQLEXPRESS;AttachDbFilename=|DataDirectory|\NORTHWND.MDF;Integ
rated Security=True;User Instance=True"
providerName="System.Data.SqlClient" />

Note: You can change the instance based on your database configuration.

Option 2:

If Option 1 does not resolve your issue, then create a new database for your sql server
configuration from current database based on scripting concept. Refer the following link to
generate database.

http://blog.sqlauthority.com/2011/05/07/sql-server-2008-2008-r2-create-script-to-copy-database-
schema-and-all-the-objects-data-schema-stored-procedure-functions-triggers-tables-views-
constraints-and-all-other-database-objects/

© 2014 Syncfusion. All rights reserved. 1027 | Page


Essential Grid for ASP.NET MVC Classic

5.14 How to: Avoid validation messages invisibility


You can follow these steps to avoid validation messages invisibility:

1.You have to set UnobtrusiveJavaScriptEnabled as “True” in the appSettings, its default value is
“False”.

[Web.config]
<appSettings>
<add key="UnobtrusiveJavaScriptEnabled" value="true"/>
</appSettings>

2.Add reference of following javascript files in _Layout.cshtml page to perform validations.

View [cshtml]

<head>
<script src="@Url.Content("~=""/Scripts/jquery.validate.min.js")"
type="text/javascript"></script>
<script
src="@Url.Content("~=""/Scripts/jquery.validate.unobtrusive.min.js")"
type="text/javascript"></script>

3.Set ValidationSummary as “True” in the View page.

View [cshtml]

@Html.ValidationSummary(true)

5.15 How to: Refresh grid contents on external button


click
Essential Grid supports refreshing the grid content by using an external button instead of the grid
pager refresh button. You must call the sendRefreshRequest() method to refresh grid contents.
The following code illustrates how to refresh grid contents on external button click.
View[cshtml]

© 2014 Syncfusion. All rights reserved. 1028 | Page


Essential Grid for ASP.NET MVC Classic

<input type="button" value="Refresh" onclick="Refresh()"/>

<script type="text/javascript">
function Refresh() {
var gridobj = $find("SampleGrid");
// “SampleGrid” is the ID of the Grid
gridobj.sendRefreshRequest();
}
</script>

5.16 How to: Get the selected row values in


ToolbarClick event
You can follow these steps to get the selected row values in ToolbarClick event.
1. Create a Grid and configure its properties as in the following code example.
View [cshtml]

@(Html.Syncfusion().Grid<EditableOrder>("OrdersGrid")
.Datasource(Model)
.Caption("Orders")
.ClientSideEvents(e => e.OnToolbarClickEvent("OnToolbarClickEvent"))
// ToolbarClick event
.ToolBar(tools =>
{
.Add("Custom", " GetSelectedRecord","Custom"); // add Custom Toolbar
button
}))

2. Create ToolbarClick event to get the selected records and pass the records to server using
Ajax post.
[JavaScript]

<script type="text/javascript">
var gridObj = null;
function OnToolbarClickEvent(sender, args) {
gridObj = sender;

© 2014 Syncfusion. All rights reserved. 1029 | Page


Essential Grid for ASP.NET MVC Classic

if (args._currentItemIndex == 3) {
// Check index for "toolbarButton"
var selectedItems = sender._selectionManager.selectedRowsCollection;
// Get selected records
sender.setJSONRecord();
var value = sender.jsonrecord;
// Set JSON record to get values of selected row
if (sender.jsonrecord.length == 0) {
alert("Please select a record.")
}
var record = { CustomerID: sender.jsonrecord[0].CustomerID,
Freight: sender.jsonrecord[0].Freight,
OrderID: sender.jsonrecord[0].OrderID,
ShipCity: sender.jsonrecord[0].ShipCity,
ShipCountry: sender.jsonrecord[0].ShipCountry
};
// Pass selected records through ajax post to server side
var json = Sys.Serialization.JavaScriptSerializer.serialize(record);
try {
$.ajax({
url: "/Home/Custom",
type: 'POST',
async: false,
contentType: 'application/json; charset=utf-8',
data: json,
dataType: 'html', // <-- to expect an html response
success: function (result) {
try{
$("#gridContainer").html(result);
} catch (ex) {
console.info('The Syncfusion scripts could not be evaluated.');
}
},
error: function (err) {

© 2014 Syncfusion. All rights reserved. 1030 | Page


Essential Grid for ASP.NET MVC Classic

console.info(err.Message);
}
});
} catch (ex) {
alert("Error: " + ex.Message);
}
}
}
</script>

[Controller]
public JsonResult Custom(string CustomerID, string OrderID, string
ShipCity, string ShipCountry, string Freight ) {
// Selected row column values are mapped here
return Json(string.Empty, JsonRequestBehavior.AllowGet);
}

5.17 How to: Set Grid height and width in Client-Side


You can follow these steps to set the Grid height and width in Client-Side,
1. Create a Grid control in the view and configure its properties.
2. In the client side, you can set the scrollbar height and width using the “gridobj” as illustrated in
the following code example,

View[Java Script]:

<input type="button" value="Change Scroll width" id="Change"


name="Change" />
<script type="text/javascript">
$('#Change').bind('click', function () {
var gridobj = $find("FlatGrid");
// Get gridobj from the GridID
gridobj.set_GridWidth(600);
// Used to set the scroller width
gridobj.set_GridHeight(150);

© 2014 Syncfusion. All rights reserved. 1031 | Page


Essential Grid for ASP.NET MVC Classic

// Used to set the scroller height


gridobj._refreshScroller();
// Need to refreshscroller to update properties of scroller
});
</script>

5.18 How to: overcome “Check whether the grid post


action is defined in controller” error when editing

You can follow these steps to avoid “Check whether the grid post action is defined in controller”
error,

1. Create a Grid control in the view and configure its properties.


2. Enable editing using Editing method and configure the editing properties such as AllowNew,
AllowEdit and AllowDelete.
3. Specify the grid editing mode using the EditMode property.
4. Specify the Primary Key property which uniquely identifies the grid record.

View[cshtml]:

@{
Html.Syncfusion().Grid<MvcApplication.Models.EditableOrder>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID").Width(90)
.TextAlign(TextAlignment.Right);
column.Add(p => p.EmployeeID).HeaderText("Employee ID").Width(90)
.TextAlign(TextAlignment.Right);
column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(90);
column.Add(p => p.OrderDate).HeaderText("Order Date").Width(90);
column.Add(p => p.Freight).HeaderText("Freight")

© 2014 Syncfusion. All rights reserved. 1032 | Page


Essential Grid for ASP.NET MVC Classic

.TextAlign(TextAlignment.Right).Format("{0:C}").Width(85);
})
.EnablePaging()
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Mappers(mapper =>
{
mapper.InsertAction("AddOrder")
.SaveAction("OrderSave")
.DeleteAction("DeleteOrder");
})
.AutoFormat(Skins.Marble)
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.Normal);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}

5. Add edit settings to the model.


6. In the controller, you need to create methods for Add, Delete and Update to avoid the error.

[Controller]

© 2014 Syncfusion. All rights reserved. 1033 | Page


Essential Grid for ASP.NET MVC Classic

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult OrderSave(EditableOrder ord)
{
// Repository action method Update used to update the records into the
data source.
OrderRepository.Update(ord);
// After saving the records into the data source, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
// Repository action method Add is used for inserting records into the
data source.
OrderRepository.Add(ord);
// After adding the record into the database, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult DeleteOrder(int OrderID)
{
// Repository action Delete() deletes the given primary value record
from the data source.
OrderRepository.Delete(OrderID);
// After deleting, refresh the grid.
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}

© 2014 Syncfusion. All rights reserved. 1034 | Page


Essential Grid for ASP.NET MVC Classic

5.19 How to: Format the Grid columns


You can follow these steps to format the Grid columns.
1. Create the Grid control in the view and configure its properties.
2. Specify the format for columns using the Format() method.

View[cshtml]

@{ Html.Syncfusion().Grid<AutoFormatting>("FormatGrid")

.Datasource(Model)

.ShowCaption(false)

.ShowRowHeader(false)

.AutoFormat(Skins.Sandune)

.Column( column =>

column.Add(c => c.Currency).HeaderText("Currency").Format("{0:C}");

column.Add(c=>c.Dates).HeaderText("Dates").Format("{0:MM/dd/yyyy
hh:mm:ss}");

column.Add(c =>c.Number).HeaderText("Number").Format("{0:# inch}");

column.Add(c=>c.Telephone).HeaderText("Telephone").Format("{0:1 - (###)
###-####}");

}).Render();

5.20 Hiding Row Header in Grid


You can hide the Grid row header by setting the property “ShowRowHeader” as false. The
following code illustrates how to hide the row header in Grid.

View[Cshtml]:

© 2014 Syncfusion. All rights reserved. 1035 | Page


Essential Grid for ASP.NET MVC Classic

@{
Html.Syncfusion().Grid<SyncfusionMvcGridApp.Models.TestModel>("Grid")
.Datasource(Model)

.ShowRowHeader(false)
}

The following screen shot illustrates a hidden Rowheader.

5.21 How to: Hide columns when exporting Grid


You can follow these steps to hide columns when exporting Grid.
1. Create the Grid control in the view and configure its properties.
2. Configure the grid toolbar to enable exporting of grid and map the ExportToExcel method.

View[cshtml]
@(Html.Syncfusion().Grid<Student>("OrdersGrid")
.Datasource(Model)
.Caption("Student")
.Column(column =>
{
column.Add(c=>c.UniversityCode).HeaderText("University
Code").TextAlign(TextAlignment.Right).Width(110);
column.Add(c => c.Title).Visible(false).HeaderText("Title");

© 2014 Syncfusion. All rights reserved. 1036 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(c=>c.CourseFees).Visible(false).HeaderText("Course
Fees").TextAlign(TextAlignment.Right).Width(90).Format("{CourseFees:c}"
);
column.Add(c=>c.CGPA).HeaderText("CGPA").TextAlign(TextAlignment.Right)
.Width(80);
column.Add(c=>c.Duration).HeaderText("Duration").TextAlign(TextAlignmen
t.Right).Width(80);
})
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.AutoFormat(Skins.Marble)
.ToolBar(toolbar =>
{
toolbar.Add(GridToolBarItems.ExcelExport, "Excel Export");
})
.Mappers(map =>
{
map.ExportExcelAction("ExportToExcel");
}))

1. Specify the file name and Excel version details in the ExportToExcel() method and you have
to set the isVisibleColumnExt property to True for export visible columns only.

[Controller]

public ActionResult ExportToExcel(PagingParams args)


{
var data = new StudentDataContext().Student.Take(200).ToList();
return data.GridExportToExcel<Student>("GridExcel.xlsx",
ExcelVersion.Excel2007, ConverterOptionsExt.Visible,false,true);
}

© 2014 Syncfusion. All rights reserved. 1037 | Page


Essential Grid for ASP.NET MVC Classic

5.22 How to: Disable sorting for specific columns in


Grid
You can follow these steps to disable sorting for specific columns in the Grid.
1. Create the Grid control in the view and configure its properties.
2. In the column builder, you can enable or disable the sorting for specific columns using
AllowSorting(bool) method as follows.

View[cshtml]:

@{Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("Grid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(P => P.CustomerID).AllowSorting(false);
col.Add(p => p.ShipCountry).AllowSorting(false);
col.Add(p => p.ShipCity);
})
.EnableSorting()
.Render();
}

View[ASPX]:

<%=Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("Grid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(P => P.CustomerID).AllowSorting(false);
col.Add(p => p.ShipCountry).AllowSorting(false);

© 2014 Syncfusion. All rights reserved. 1038 | Page


Essential Grid for ASP.NET MVC Classic

col.Add(p => p.ShipCity);


})
.EnableSorting()
.Render();
%>

5.23 How to: Get properties of the grid


You can get all the properties of grid from the gridobj. The following code example illustrates
how to get AllowPaging property in the client side.

View[cshtml]

<input type="button" value="AllowPaging" id="AllowPaging"


name="AllowPaging" />
<script type="text/javascript">
$('#AllowPaging').bind('click', function () {
var gridObj = $find('SampleGrid');
// SampleGrid is the grid ID
alert("AllowPaging :" + gridObj.get_AllowPaging());
// AllowPaging property value can get from gridObj.get_AllowPaging()
});
</script>

5.24 How to: Get selected records in another view


You can follow these steps to get selected records in another view.
1. Create a Grid control in the view and configure its properties.
2. In the view, you have to create OnToolbarClickEvent Client-Side event and this event is
triggered when the you click the selectedrecords button.

View[cshtml]:

@{ Html.Syncfusion().Grid<SyncGrid.Models.Order>("GridOrder")
.Datasource(Model)
.Caption("Orders")

© 2014 Syncfusion. All rights reserved. 1039 | Page


Essential Grid for ASP.NET MVC Classic

.Column(column => {
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.OrderDate).HeaderText("Order
Date").Format("{OrderDate:MM/dd/yyyy}");
column.Add(p => p.Freight).HeaderText("Freight");
})
.EnablePaging()
.ToolBar(tools =>
{
tools.Add("SelectedOrders", "Selected Orders", "SelectedOrderItem");
})
.ClientSideEvents(e =>
{
e.OnToolbarClickEvent("toolbarClickEvent");
})
.Render();
}

1. You can get the selected rows from the selectedRows () method in the client side. Then, you
have to serialize the selected records and pass to the controller action.

View[Java Script]:

<script type='text/javascript'>
var selectedRecords = [];
function toolbarClickEvent(sender, args) {
var gridObj = sender;
var value = gridObj.selectedRows();
var record = null;
$.each(value, function (index, val) {
record = new Syncfusion.Mvc.Grid.SelectionEventArgs({ row: val },
gridObj.get_VisibleColumnName()).record;
selectedRecords.push(record);

© 2014 Syncfusion. All rights reserved. 1040 | Page


Essential Grid for ASP.NET MVC Classic

});
var form = $("<form method='post' action='/Home/SelectedOrders'>
</form>").append("<input name='orders' value='" +
Sys.Serialization.JavaScriptSerializer.serialize
(selectedRecords) + "'/>")
form.appendTo(document.body);
form.submit();
}
</script>

2. In the controller, you get the serialized selected records by the SelectedOrders action and you
have to deserialize the records and pass it to another view page.

[Controller]:

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult SelectedOrders(string orders)
{
var data1 = new JavaScriptSerializer().Deserialize(orders,
typeof(IEnumerable<Order>));
ViewData["OrdersMsg"] = orders;
return View("SelectedOrders", data1);
}

View[Cshtml]:

@model IEnumerable<SyncGrid.Models.Order>
<table>
<tr>
<th>Customer ID</th>
<th>Order Date</th>
<th>Freight</th>
</tr>
@foreach (var item in Model) {

© 2014 Syncfusion. All rights reserved. 1041 | Page


Essential Grid for ASP.NET MVC Classic

<tr>
<td>@Html.DisplayFor(modelItem => item.CustomerID)</td>
<td>@Html.DisplayFor(modelItem => item.OrderDate)</td>
<td>@Html.DisplayFor(modelItem => item.Freight)</td>
</tr>
}
</table>

5.25 How to: Show tooltip on Grid Cell MouseHover in Server


mode
You can follow these steps to show tooltip on Grid Cell MouseHover in Server mode.
1. Create a Grid control in the view and configure its properties.

View[cshtml]:

@{Html.Syncfusion().Grid<MvcSampleApplication.Models.EditableOrder>("Gr
id")

.Datasource((IEnumerable<MvcSampleApplication.Models.EditableOrder>)Vie
wData["Datasrc"]).Column(cols =>
{
cols.Add(c => c.OrderID);
cols.Add(c => c.ShipCity);
cols.Add(c => c.ShipCountry);
cols.Add(c => c.Freight);
cols.Add(c => c.CustomerID);
})
.EnablePaging()
.QueryCellInfo(
cell => Html.RenderAction("onQueryCellAction", "Home", new { args =
cell })) .Render();
}

© 2014 Syncfusion. All rights reserved. 1042 | Page


Essential Grid for ASP.NET MVC Classic

2. You have to set the tooltip for the grid cell using QueryCellInfo as illustrated in the following
code example.

[Controller]

public void onQueryCellAction(GridTableCell<EditableOrder> args)


{
if (args.TableCellType == GridTableCellType.RecordFieldCell ||
args.TableCellType == GridTableCellType.AlternateRecordFieldCell)
{
args.HtmlAttributes["Title"] = args.Text;
}
}

3. If you are using Filtering/Sorting/Paging actions.You have to rebind the Querycellinfo property
again to the Grid in the post action,

[Controller]

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
List<EditableOrder> data =
OrderRepository.GetAllRecords().Take(10).ToList();
var engine = data.GridActions<EditableOrder>() as
GridHtmlActionResult<EditableOrder>;
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;}

5.26 How to: Show tooltip on Grid Cell MouseHover in


JSON mode
You can follow these steps to show tooltip on Grid Cell MouseHover in JSON mode,
1. Create a Grid control in the view and configure its properties.

View[cshtml]

© 2014 Syncfusion. All rights reserved. 1043 | Page


Essential Grid for ASP.NET MVC Classic

@{Html.Syncfusion().Grid<MvcSampleApplication.Models.EditableOrder>("En
tityGrid")

.ActionMode(Syncfusion.Mvc.Grid.ActionMode.JSON)
.Column(cols =>
{
cols.Add(c => c.OrderID);
cols.Add(c => c.ShipCity);
cols.Add(c => c.ShipCountry);
cols.Add(c => c.Freight);
cols.Add(c => c.CustomerID);
})
.EnablePaging()
.EnableGrouping()
.EnableSorting()
.ClientSideEvents(events =>
{
events.QueryCellInfo("QueryCellInfoHandler");
})
.Render();
}

2. In the view, you have to create the QueryCellInfo Client-Side event and set the tooltip for grid
cell on the client side. Refer the following code example to create QueryCellInfo.
<script type="text/javascript">
function QueryCellInfoHandler(sender, args) {
if (args.Element.className == "RowCell")
$(args.Element).attr('Title', args.Text);
}
</script>

© 2014 Syncfusion. All rights reserved. 1044 | Page


Essential Grid for ASP.NET MVC Classic

5.27 How to: Format the cells through QueryCellInfo


event
Essential Grid provides support to format cells at run time using the QueryCellInfo() events. You
can follow these steps to format the cells through QueryCellInfo event,
1. To perform custom formatting in the cell level.Configure the QueryCellInfo() action as shown in
the following code example.

[Controller]

public void onQueryCellAction(GridTableCell<EditableOrder> args)


{
if (args.TableCellType == GridTableCellType.RecordFieldCell ||
args.TableCellType == GridTableCellType.AlternateRecordFieldCell)
{
if (args.Column.MappingName == "EmployeeID")
{
if (args.Data.EmployeeID >= 4)
{
args.HtmlAttributes["style"] = "color:Blue;background-
color:Chocolate;";
args.Text = "<span style='display:none;'>" + args.Text + "</span>" +
"6";
}
else
{
args.HtmlAttributes["style"] = "color:#ac0c0c;background-
color:Bisque;";
}
}
}
}

2. In the view, you can use Html.Renderaction in QueryCellInfo() to render the result directly.

View[cshtml]
@{
Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("SampleGrid"
)
.Datasource(Model)

© 2014 Syncfusion. All rights reserved. 1045 | Page


Essential Grid for ASP.NET MVC Classic

.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(p => p.EmployeeID);
col.Add(P => P.CustomerID);
col.Add(p => p.ShipCountry);
col.Add(p => p.Freight);
})
.QueryCellInfo(
cell => Html.RenderAction("onQueryCellAction", "GridBuilder", new {
args = cell }) //Action name, controller name and cell
)
.EnablePaging()
.EnableSorting()
.Render(); }

3. To make it work with paging and sorting actions, create a Post method for Index actions and
bind the data source to the grid as shown in the following code example.

[Controller]

public ActionResult ServerPaging()


{
var data = OrderRepository.GetAllRecords();
return View(data);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult ServerPaging(PagingParams args)
{
IEnumerable data = OrderRepository.GetAllRecords();
var engine = data.GridActions<EditableOrder>() as
GridHtmlActionResult<EditableOrder>;
//Rebinding the QueryCellInfo
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;
}

© 2014 Syncfusion. All rights reserved. 1046 | Page


Essential Grid for ASP.NET MVC Classic

5.28 How to: Get custom theme for multiple (Grid,


Tools, Schedule) controlsHow to: Move Grid rows Up
and Down using Button
You can follow these steps to move Grid rows Up and Down using Button,
1.Configure the grid with its properties and events as illustrated in the following code example.

[Cshtml]

<div>
<p style="color: Red;">
Select any row and click Up/Down Arrows to move row</p>
<p style="color: Red;">
Click save to store position of the records on database</p>
<img src="../../Content/Up.png" class="UpRows" />
<img src="../../Content/Down.png" class="DownRows" />
<img src="../../Content/save.png" class="SaveOrders" />
</div>

@(Html.Syncfusion().Grid<Customer>("TestGrid")
.Caption("Employee Grid")
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.CustomerID);
column.Add(p => p.CompanyName);
column.Add(p => p.ContactName);
column.Add(p => p.Address);
})

.ClientSideEvents(events=>events.OnActionSuccess("Paging"))
.EnablePaging())

2.In load event, set rowIndex of table ‘tr’ to data attribute as index.
Sys.Application.add_load(function () {

© 2014 Syncfusion. All rights reserved. 1047 | Page


Essential Grid for ASP.NET MVC Classic

$("#TestGrid_Table").find('tr').each(function () {
$(this).data("index", ($(this)[0].rowIndex + 1));
});
var order = new Array();
});

3.Using SelectedRowsCollection, you can retreive the selected records from GridObject and
parse the selectedrow index to move up or down the rows.Using selectedrow index, the record
cells can be moved Up or Down except in the first column cells.

[JavaScript]:

Sys.Application.add_load(function () {
var gridObj = $find("TestGrid");
var order = new Array();
$('.DownRows').click(function () {
var Index = gridObj._selectionManager.selectedRowsCollection;
DownRows($("#TestGrid_Table").find('tr')[parseInt(Index)]);
gridObj._selectionManager.deselectRow(parseInt(Index) + 1);
gridObj._selectionManager.selectRow(parseInt(Index));
});
$('.UpRows').click(function () {
var gridObj = $find("TestGrid");
var Index = gridObj._selectionManager.selectedRowsCollection;
UpRows($("#TestGrid_Table").find('tr')[parseInt(Index)]);
gridObj._selectionManager.deselectRow(parseInt(Index) - 1);
gridObj._selectionManager.selectRow(parseInt(Index));
});
});

function UpRows(row) {
var prevRow = row.previousSibling;
if (prevRow) {
var index = $(prevRow).data('index');

© 2014 Syncfusion. All rights reserved. 1048 | Page


Essential Grid for ASP.NET MVC Classic

// first columns cells excluded as optional


var PrevSiblings = $(prevRow).find("td[class*='RowCell']").slice(1);
var CurrentSiblings = $(row).find("td[class*='RowCell']").slice(1);

$(PrevSiblings).insertAfter($(row).find("td[class*='RowCell']").eq(0));

$(CurrentSiblings).insertAfter($(prevRow).find("td[class*='RowCell']").
eq(0);
$(row).data('index', $(row).data('index'));
$(prevRow).data('index', index);
}
}

function DownRows(row) {
var nextRow = row.nextSibling;
if (nextRow) {
var index = $(nextRow).data('index');
// first columns cells excluded here is optional
var NextSiblings = $(nextRow).find("td[class*='RowCell']").slice(1);
var CurrentSiblings = $(row).find("td[class*='RowCell']").slice(1);

$(NextSiblings).insertAfter($(row).find("td[class*='RowCell']").eq(0));

$(CurrentSiblings).insertAfter($(nextRow).find("td[class*='RowCell']").
eq(0);
$(row).data('index', $(row).data('index'));
$(nextRow).data('index', index);
}
}

5.29 How to: Hide filter icon in grid table header


Set the display property of “.HeaderCell .FilterIcon” selector to “none” in your site.css file. Refer
the following code example:

© 2014 Syncfusion. All rights reserved. 1049 | Page


Essential Grid for ASP.NET MVC Classic

[CSS]

.HeaderCell .FilterIcon

display:none !important;

5.30 How to: Set the height of the grid rows


You can follow these steps to set height for the grid rows,
1. Create a Grid control in the view and configure its properties.
2. You have to change the grid row height by using CSS as illustrated in the following code
example.

[CSS]

<style type="text/css">
.Syncfusion-Grid-Core .RowCell, .Syncfusion-Grid-Core .EmptyCell,
.Syncfusion-Grid-Core tr[class*="ChildRow"] > .ChildGrid
{
line-height: 3.3em!important;
}
</style>

5.31 How to: Use one column data value in another


column
You can follow these steps to use one column data value in another column.
1.Create a Grid control in the view and configure its properties.
2. Using “QueryCellInfo” event, you can use the value of one column to another column.
For Example: The value of “OrderID” is used in “EmployeeID” column by using
args.Data.OrderID in the following code example.

View [cshtml]

@{Html.Syncfusion().Grid<JSONOrder>("SampleGrid")
.Datasource(Model)
.Caption("Orders")

© 2014 Syncfusion. All rights reserved. 1050 | Page


Essential Grid for ASP.NET MVC Classic

.QueryCellInfo(cell => Html.RenderAction(“onQueryCellAction”,”Home”,


new { args= cell}))
.Render();}

[Controller]

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
IEnumerable data = GridOrders;
var engine = data.GridActions<JSONOrder>() as GridHtmlActionResult<JSON
Order>;
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;
}
public void onQueryCellAction(GridTableCell<JSONOrder> args)
{
if (args.TableCellType == GridTableCellType.RecordFieldCell ||
args.TableCellType == GridTableCellType.AlternateRecordFieldCell)
{
if (args.Column.MappingName == "EmployeeID")
{
args.Text = "<a class='TemplateCell'
href='Home/Load?id="+args.Data.OrderID+"'>" + args.Data.EmployeeID +
"</a>";
}

5.32 How to: Custom server paging with initial grouping


You can follow these steps to custom server paging with initial grouping,

1. Configure a grid and enable the custom binding mode using EnableOnDemand property.

2. Set TotalRecordCount, if the paging feature is enabled.

3. Add GroupDescriptors for initial grouping. Refer the following code example:

© 2014 Syncfusion. All rights reserved. 1051 | Page


Essential Grid for ASP.NET MVC Classic

[Controller]
public ActionResult Index()
{
var model = GetGridPropertiesModel(0);
return View(model);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
var data = UserModel.GetUsersPage(args.StartIndex);
return data.GridActions<ExportUserObject>();
}
private static GridPropertiesModel<ExportUserObject>
GetGridPropertiesModel
(int startIndex)
{
var totalCount = 0;
var data = UserModel.GetUsersPage(startIndex, ref totalCount);
var model = new GridPropertiesModel<ExportUserObject>
{
DataSource = data,
Caption = "Users",
AllowPaging = true,
AllowSorting = true,
AllowGrouping=true,
TotalRecordsCount = totalCount,
PageSetting = new PageSettings()
{
AllowPaging = true,
PageSize = Constants.PageSize,
PageCount = Constants.PageCount,
CurrentPage = 1,
},
EnableOnDemand = true,

© 2014 Syncfusion. All rights reserved. 1052 | Page


Essential Grid for ASP.NET MVC Classic

};
//Group by the first name.
model.GroupDescriptors.Add("FirstName");
return model;
}

5.33 How to: Use alternate row color background


You can follow these steps to use alternate row color background,

1. Create a Grid control in the view and configure its properties.

2. To activate the alternate row color feature in the view, set the .EnableAlternateRowStyling()
property.

View[cshtml]

@( Html.Syncfusion().Grid<Order>("Grid")
.Datasource(Model)
.Caption("Orders")
.EnableAlternateRowStyling()
.EnablePaging()
.AutoFormat(Skins.Sandune)
.Column( columns => {
columns.Add(p => p.OrderID).HeaderText("Order ID");
columns.Add(p => p.CustomerID).HeaderText("Customer ID");
columns.Add(p => p.EmployeeID).HeaderText("Employee ID");
columns.Add(P => P.ShipCountry).HeaderText("Ship Country");
columns.Add(p => p.ShipCity).HeaderText("Ship City");
}) )

5.34 How to: Right align summary row values


You can follow these steps to right align the summary row values,

1. Modify the style of summary row class.

© 2014 Syncfusion. All rights reserved. 1053 | Page


Essential Grid for ASP.NET MVC Classic

[CSS]

<style type="text/css">

.Summary

text-align:right!important;

</style>

2. Set text-align to left for the specific Summary row cells (first cell) in Client-Side OnLoad event.

[JavaScript]

<script type="text/javascript">
function load(sender, args) {
var context = $find('Summary_Grid'); // Find the gridobject
var GridSummary = $(context.get_element()).find('table.GridSummary');
if (GridSummary.length > 0) {
var GridSummaryTR = $(GridSummary[0]).find('tr');
for (var i = 0; i < GridSummaryTR.length; i++) {
varGridSummaryCol=$(GridSummaryTR[i]).children('td.Summary:eq(1)').css(
'cssText', 'text-align: left !important')
}
}
}
</script>

5.35 How to: Format the values in the filter dialog.


AllowFormatFiltering property is used to format the filtering dialog values in grid. Refer
to the following code example:
Controller]

GridFiltering gf = new GridFiltering()


{

© 2014 Syncfusion. All rights reserved. 1054 | Page


Essential Grid for ASP.NET MVC Classic

AllowFiltering=true,
FilterMode = FilterMode.Default,
AllowFormatFiltering=true,
};

5.36 How to: Add New, Delete and Update multiple grids
uing external button
You can follow these steps to add new, delete and update multiple grids uing external button.
1. Create a Grid control in the view and configure its properties.

View[Grid.Cshtml]
Grid1:
@{Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("SampleGri
d")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(P => P.CustomerID);
col.Add(p => p.ShipCountry);
col.Add(p => p.ShipCity);
})
.PageSettings(page => { page.PageSize(7); })
.EnablePaging()
.ToolBar(
tool =>
{
tool.Add(GridToolBarItems.AddNew);
tool.Add(GridToolBarItems.Edit);
tool.Add(GridToolBarItems.Delete);
tool.Add(GridToolBarItems.Update);
tool.Add(GridToolBarItems.Cancel);
}

© 2014 Syncfusion. All rights reserved. 1055 | Page


Essential Grid for ASP.NET MVC Classic

)
.Mappers(map =>
{
map.Action("ServerPaging")
.SaveAction("BulkSave");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.ManualExcel);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}
Grid2:
@{Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("SampleGri
d1")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(col =>
{
col.Add(p => p.OrderID);
col.Add(P => P.CustomerID);
col.Add(p => p.ShipCountry);
col.Add(p => p.ShipCity);
})
.PageSettings(page => { page.PageSize(7); })
.EnablePaging()
.ToolBar(
tool =>
{

© 2014 Syncfusion. All rights reserved. 1056 | Page


Essential Grid for ASP.NET MVC Classic

tool.Add(GridToolBarItems.AddNew);
tool.Add(GridToolBarItems.Edit);
tool.Add(GridToolBarItems.Delete);
tool.Add(GridToolBarItems.Update);
tool.Add(GridToolBarItems.Cancel);
}
)
.Mappers(map =>
{
map.Action("ServerPaging")
.SaveAction("BulkSave1");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.ManualExcel);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}

2. Create a button element in the view page and refer the following code example for the button
click event.
View[Grid.Cshtml]
<input type="button" value="Add" id="Add" name="Add" />
<input type="button" value="Edit" id="Edit" name="Edit" />
<input type="button" value="Delete" id="Delete" name="Delete" />
<input type="button" value="Save" id="Save" name="Save" />
<input type="button" value="Cancel" id="Cancel" name="Cancel" />

<script type="text/javascript">
$('#Add').bind('click', function () {

© 2014 Syncfusion. All rights reserved. 1057 | Page


Essential Grid for ASP.NET MVC Classic

var gridObj = $find('SampleGrid');


gridObj.sendAddNewRequest();
var gridObj1 = $find('SampleGrid1');
gridObj1.sendAddNewRequest();
});
$('#Edit').bind('click', function () {
var gridObj = $find('SampleGrid');
gridObj._ToolBarEditRecordClick();
var gridObj1 = $find('SampleGrid1');
gridObj1._ToolBarEditRecordClick();
});
$('#Delete').bind('click', function () {
var gridObj = $find('SampleGrid');
gridObj.sendDeleteRequest();
var gridObj1 = $find('SampleGrid1');
gridObj1.sendDeleteRequest();
});
$('#Save').bind('click', function () {
var gridObj = $find('SampleGrid');
gridObj.sendSaveRequest();
var gridObj1 = $find('SampleGrid1');
gridObj1.sendSaveRequest();
});
$('#Cancel').bind('click', function () {
var gridObj = $find('SampleGrid');
gridObj.sendCancelRequest();
var gridObj1 = $find('SampleGrid1');
gridObj1.sendCancelRequest();
});
</script>

2.In the controller, create a method to save changes. Following code example shows how to
create the repository method BulkSave() to update records to the data source.
[Controller]

© 2014 Syncfusion. All rights reserved. 1058 | Page


Essential Grid for ASP.NET MVC Classic

[AcceptVerbs(HttpVerbs.Post)]
Public ActionResult BulkSave([Bind(Prefix =
"updatedRecords")]IEnumerable<EditableOrder> orders, [Bind(Prefix =
"addedRecords")]IEnumerable<EditableOrder> addRcrds, [Bind(Prefix =
"deletedRecords")]IEnumerable<EditableOrder> delRcrds)
{
//Repository action method Update used to update the records into
datasource.
if (orders != null)
OrderRepository.Update(orders);
if (addRcrds != null)
OrderRepository.Add(addRcrds);
if (delRcrds != null)
OrderRepository.Delete(delRcrds);
//After saving the records into datasource, refresh the grid
var data = OrderRepository.GetAllRecords();
return data.GridJSONActions<EditableOrder>();
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult BulkSave1([Bind(Prefix =
"updatedRecords")]IEnumerable<EditableOrder> orders, [Bind(Prefix =
"addedRecords")]IEnumerable<EditableOrder> addRcrds, [Bind(Prefix =
"deletedRecords")]IEnumerable<EditableOrder> delRcrds)
{
//Repository action method Update used to update the records into
Datasource.
if (orders != null)
OrdersData.Update1(orders);
if (addRcrds != null)
OrdersData.Add1(addRcrds);
if (delRcrds != null)
OrdersData.Delete(delRcrds);
//After saving the records into datasource refresh the grid
var data = OrdersData.GetAllRecords();
return data.GridJSONActions<OrderEdit>();

© 2014 Syncfusion. All rights reserved. 1059 | Page


Essential Grid for ASP.NET MVC Classic

5.37 How to: Save the Grid Content using an External


Button.
Essential Grid allows saving the grid content by using an external button instead of the tool bar
button. You have to call the sendSaveRequest() method for saving, as illustrated in the following
code example.

[View]

<input type="button" value="Save Record" id="Save"


onclick="SaveRequest();"/>
<script type="text/javascript">
function SaveRequest() {
var gridObj = $find("OrdersGrid"); //Get the gridobj from the GridID
gridObj.sendSaveRequest()
}
</script>

5.38 How to: Change dropdown to textbox cell for


particular cells when celledit type is dropdown
You can follow these steps to change the dropdown to textbox cell for particular cells when
celledit type is dropdown,
1. Create a Grid control in the view and configure its properties.
2. In the view, create onCellEdit Client-Side event and this event is triggered while editing the
grid.

View[cshtml]

@{ Html.Syncfusion().Grid<Sample.Models.EditableOrder>("OrderGrid")
.Datasource(Model)
.ActionMode(ActionMode.JSON)
.Caption("Orders")
.Column(col =>
{

© 2014 Syncfusion. All rights reserved. 1060 | Page


Essential Grid for ASP.NET MVC Classic

col.Add(c => c.OrderID).HeaderText("OrderID");


col.Add(c => c.EmployeeID).HeaderText("Employee ID");
col.Add(c => c.CustomerID).HeaderText("CustomerID");
col.Add(c => c.ShipCity).HeaderText("Ship
City").CellEditType(CellEditType.DropdownEdit);
col.Add(c => c.ShipName).HeaderText("Ship Name");
})
.EnablePaging()
------
------
.ClientSideEvents(evnts =>
{
evnts.OnCellEdit("onCellEdit");
})
.Render();
}

2. In client side, select “ShipCity” cell and replace it with textbox with the cellvalue only if the
CustomerID is equal to “VINET”.
<script type="text/javascript">
function onCellEdit(sender, args) {
if (args.colObj.Name == "ShipCity") {
if (sender._currentDataItem.CustomerID == "VINET") {

$(sender._editTD).find("select#ShipCity").replaceWith('<input
type="text" value="' + sender._currentDataItem.ShipCity + '"
name="ShipCity" id="ShipCity" data-val-length-max="15" data-val-
length="ShipCity must be 15 characters." data-val="true">');
}
}
}
</script>

© 2014 Syncfusion. All rights reserved. 1061 | Page


Essential Grid for ASP.NET MVC Classic

5.39 How to: Hide MasterCellCollapse/Expand in


Hierarchy Grid
MasterCellCollapse/Expand can be hidden based on some condition using Client-Side events
“OnLoad”, “OnActionSuccess” and “OnRecordExpanding”. In the following code example, the
hidding is based on the primary key value mastercells.

View [cshtml]

@{
Html.Syncfusion().Grid<MvcSampleBrowser.Models.EditableOrder>("GridSrc"
)
.Datasource(Model)
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
})
.ClientSideEvents(eve =>
{
eve.OnRecordExpanding("OnExpanding");
eve.OnLoad("success");
eve.OnActionSuccess("success");
})
.ChildGrid(child =>
{
child.ChildGridTemplate(Html.Syncfusion().Grid<
OrderDetailEdit>("ChildGrid_${OrderID}")
.Caption("OrderDetails Grid")
.Column(c =>
{
c.Add(p => p.OrderID).HeaderText("Order ID");
c.Add(p => p.ProductID).HeaderText("Product ID");
c.Add(p => p.UnitPrice).HeaderText("Unit Price");
})
.ToChildGridTemplate());

© 2014 Syncfusion. All rights reserved. 1062 | Page


Essential Grid for ASP.NET MVC Classic

})
.Render();
}

[JavaScript]

<script type="text/javascript">
function success(sender, args) {
var array = ["10251", "10252", "10258"]; // list of primary keys to
hide/ expand/collapse.
var trs = $("#" + sender.get_element().id + "_Table tr");
$.each(array, function (index, val) {
$(trs).find("td:contains(" + val +
")").parent().find("td.MasterCellCollapse div").css("background-image",
"none");
});
}
function OnExpanding(sender, args) {
var array = ["10251", "10252", "10258"]; // list of primary keys to
hide/ expand/collapse
var trs = $("#" + sender._ID + "_Table tr");
$.each(array, function (val) {
if (args.data.OrderID == array[val]) {
args.cancel = true;
$(trs).find("td:contains("+args.data.OrderID+")").parent().find("td.Mas
terCellCollapse div").css("background-image", "none");
}
});
}
</script>

5.40 How to: Hide GroupHeaderArea when Grouping is


defined in code
Grid GroupDropArea can be hidden by setting “ShowGroupDropArea” property to “false”. Refer
the following code example:

View [Cshtml]

© 2014 Syncfusion. All rights reserved. 1063 | Page


Essential Grid for ASP.NET MVC Classic

@{
Html.Syncfusion().Grid<SyncfusionMvcGridApp.Models.TestModel>("Grid")
.Datasource(Model)
.EnableGrouping()
.Grouping(group => { group.ShowGroupDropArea(false); })
}

View [ASPX]

<%=
Html.Syncfusion().Grid<SyncfusionMvcGridApp.Models.TestModel>("Grid")
.Datasource(Model)
.EnableGrouping()
.Grouping(group => { group.ShowGroupDropArea(false); })
%>

5.41 How to: Assign datasource for a DropdownEdit at


clientside
You can follow these steps to assign datasource for a Dropdown.
1. Set the CellEditType as DropDownEdit in grid column and handle the events for updating drop
down values.

View[cshtml]

@{Html.Syncfusion().Grid<EditableOrder>("SampleGrid")
.ActionMode(ActionMode.Server)
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);

© 2014 Syncfusion. All rights reserved. 1064 | Page


Essential Grid for ASP.NET MVC Classic

col.Add(c => c.CustomerID);


col.Add(c => c.ShipCountry).CellEditType(CellEditType.DropdownEdit);
col.Add(c => c.Freight);
})
.ClientSideEvents(events =>
{
events.OnActionSuccess("SetdropDownData");
events.OnActionBegin("GetdropDownData");
})
.Render();
}

2.Populate external country list for the dropdown values and return the values as JSON from the
GetCountries() method.

[Controller]

public IEnumerable<SelectListItem> CountryList


{
get
{
List<SelectListItem> type = new List<SelectListItem>();
type.Add(new SelectListItem
{
Selected = true,
Text = "Switzerland",
Value = "Switzerland"
});
------
------
return type;
}
}

public ActionResult GetCountries()

© 2014 Syncfusion. All rights reserved. 1065 | Page


Essential Grid for ASP.NET MVC Classic

return Json(CountryList, JsonRequestBehavior.AllowGet);


}

3. In the OnActionBegin event you get the countries list from GetCountries method using $.ajax
and assign the value to dropDownOptions variable. In the OnActionSuccess event, you can
append the country list items for the specified column.

[ASPX]

<script type="text/javascript">
var dropDownOptions = null;
function GetdropDownData(sender, args) {
$.ajax({
type: "POST",
url: "Home/GetCountries",
dataType: "json",
success: function (data) {
dropDownOptions = data;
}
});
}
function SetdropDownData(sender, args) {
if (dropDownOptions != null)
UpdateDropDown(dropDownOptions);
}
function UpdateDropDown(data) {
$("#ShipCountry").empty();
$.each(data, function (index, val) {
var optionTag = $("<option></option>");
$(optionTag).val(val.Value).text(val.Text);
$("#ShipCountry").append(optionTag);
});
}
</script>

© 2014 Syncfusion. All rights reserved. 1066 | Page


Essential Grid for ASP.NET MVC Classic

5.42 How to: Update the cell value at client side


Get the JSON data of grid using get_dataSource() Client-Side method and process JSON data.
Then, set the processed JSON data to grid using set_dataSource() Client-Side method in JSON
mode. Refer the following code example:

View [cshtml]
<input type="button" id="Button" name="Copy" value="Copy"
onclick="CopyTo()"/>
@(Html.Syncfusion().Grid<EditableOrder>("OrdersGrid")
.ActionMode(Syncfusion.Mvc.Grid.ActionMode.JSON)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.EmployeeID).HeaderText("Employee Id");
column.Add(c => c.ShipName).HeaderText("Ship Name");
column.Add(c => c.ShipCity).HeaderText("Ship City");
column.Add(c => c.Freight).HeaderText("Freight");
})
)

View [ASPX]

<input type="button" id="Button" name="Copy" value="Copy"


onclick="CopyTo()"/>

<%= Html.Syncfusion().Grid<EditableOrder>("OrdersGrid")
.ActionMode(Syncfusion.Mvc.Grid.ActionMode.JSON)
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.EmployeeID).HeaderText("Employee Id");

© 2014 Syncfusion. All rights reserved. 1067 | Page


Essential Grid for ASP.NET MVC Classic

column.Add(c => c.ShipName).HeaderText("Ship Name");


column.Add(c => c.ShipCity).HeaderText("Ship City");
column.Add(c => c.Freight).HeaderText("Freight");
})
%>

View [Java Script]


<script type="text/javascript">
function CopyTo() {
var gridObj = $find("OrdersGrid"); //get gridobj of the OrdersGrid
var jsonMgr = gridObj.get_jsonModeMgr();
var jsonData = jsonMgr.get_dataSource();
$.each(jsonData, function (index, value) {
jsonData[index]["ShipCity"] = jsonData[index]["ShipName"];
// ShipName columns values are copied to ShipCity column
});
jsonMgr.set_dataSource(jsonData);
}
</script>

5.43 How to: Change entire column values in client side.


You can follow these steps to change entire column values in client side,
1.Create a Grid control in the view and configure its properties.

View[cshtml]
@{Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("Grid")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(col =>
{
col.Add(p => p.OrderID);

© 2014 Syncfusion. All rights reserved. 1068 | Page


Essential Grid for ASP.NET MVC Classic


})
.EnablePaging()
.Render();
}

View[ASPX]

<%=Html.Syncfusion().Grid<EditingSample.Models.EditableOrder>("Grid")
.Datasource(Model)
.Caption("Orders")
.ActionMode(ActionMode.JSON)
.Column(col =>
{
col.Add(p => p.OrderID);

})
.EnablePaging()
.Render();
%>

2. In the view page, use a dropdown box to change the grid column values.

View[cshtml]
<select name="ShipCountry" id="ShipCountry" class="ShipCountry">
<option value="Argentina" selected="selected">Argentina</option>
<option value="Austria">Austria</option>
<option value="Belgium">Belgium</option>
<option value="Brazil">Brazil</option>
<option value="Canada">Canada</option>
<option value="Denmark">Denmark</option>
<option value="USA">USA</option>
</select>

© 2014 Syncfusion. All rights reserved. 1069 | Page


Essential Grid for ASP.NET MVC Classic

3. In client side, get the grid contents using “get_dataSource” method in JSON mode and
process (modifying the entire column values) the data. Then, refresh the grid in client-side using
“clientSideRefresh” method.

View [Java Script]


<script type="text/javascript">
$('.ShipCountry').change(function () {
var gridobj = $find('SampleGrid'); //find the gridobject
var griddata = gridobj.get_jsonModeMgr().get_dataSource();
$.each(griddata, function (index, val) {
griddata[index].ShipCountry = $('.ShipCountry').val();
});
gridobj.get_jsonModeMgr().clientSideRefresh();
});
</script>

Adding Controls in Dialog Template – Server Mode


You can follow these steps to add Controls in Dialog Template – Server Mode.
1. Configure grid with dialog template properties.

View [Cshtml]
@{ Html.Syncfusion().Grid<TestModel>("Grid")
.ActionMode(ActionMode.Server)
.Datasource(Model)
.AutoFormat(Skins.Office2007Silver)
.Column(col =>
{
col.Add(c => c.TestId);
col.Add(c => c.Name);
})
.Editing(edit =>
{
edit.Dialog(dialog =>
{
dialog.Height(320);
dialog.Width(320);

© 2014 Syncfusion. All rights reserved. 1070 | Page


Essential Grid for ASP.NET MVC Classic

dialog.Position(DialogPositions.Center);
dialog.Show(DialogAnimations.bounce);
dialog.Hide(DialogAnimations.fold);
});
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.DialogTemplate);

edit.DialogModeEditorTemplate("EditTemplate");

edit.PrimaryKey(key => key.Add(c => c.TestId));


}).Render(); }

View [ASPX]
<%= Html.Syncfusion().Grid<TestModel>("Grid")
.ActionMode(ActionMode.Server)
.Datasource(Model)
.AutoFormat(Skins.Office2007Silver)
.Column(col =>
{
col.Add(c => c.TestId);
col.Add(c => c.Name);
})
.Editing(edit =>
{
edit.Dialog(dialog =>
{
dialog.Height(320);
dialog.Width(320);
dialog.Position(DialogPositions.Center);
dialog.Show(DialogAnimations.bounce);
dialog.Hide(DialogAnimations.fold);

© 2014 Syncfusion. All rights reserved. 1071 | Page


Essential Grid for ASP.NET MVC Classic

});
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.DialogTemplate);
edit.DialogModeEditorTemplate("_EditTemplate");
edit.PrimaryKey(key => key.Add(c => c.TestId));
}).Render();
%>

2. Configure edit item template with model and pass values for “DropDownListFor” control.

View [Razor]
@model TestModel
<fieldset>
@Html.HiddenFor(model => model.TestId)
<div class="editor-label">
@Html.LabelFor(model => model.Name)
</div>
<div class="editor-field">
@Html.EditorFor(model => model.Name)
@Html.ValidationMessageFor(model => model.Name)
</div>
<div class="editor-label">
@Html.LabelFor(model => model.AList)
</div>
<div class="editor-field">
@Html.DropDownListFor(model => model.AListId, Model.AList)
</div>
</fieldset>

View [ASPX]

© 2014 Syncfusion. All rights reserved. 1072 | Page


Essential Grid for ASP.NET MVC Classic

<fieldset>
<div class="editor-label">
<%= Html.LabelFor(model => model.Name) %>
</div>
<div class="editor-field">
<%= Html.TextBoxFor(model => model.Name) %>
<%= Html.ValidationMessageFor(model => model.Name) %>
</div>
<div class="editor-label">
<%= Html.LabelFor(model => model. AList) %>
</div>
<div class="editor-field">
<%= Html.DropDownListFor(model => model.AListId, Model.AList)) %>
</div>
</fieldset>

2. Configure the grid actions as shown in the following code example.

[Controller]
public ActionResult Index()
{
var modelList = TestModel.GetAll();
return View(modelList);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args, int? TestId)
{
var modelList = TestModel.GetAll();
RequestType currentRequest =
(RequestType)Convert.ToInt32(args.RequestType);
// Check if the current request is an Edit request and if the edit mode
is
In Template form mode. Then, call the PartialView() to render the
template.
if (currentRequest == RequestType.BeginEdit)
{

© 2014 Syncfusion. All rights reserved. 1073 | Page


Essential Grid for ASP.NET MVC Classic

TestModel ord = TestModel.Select(TestId);


return PartialView("_EditTemplate", ord);
}
else if (currentRequest == RequestType.BeginAddNew)
{
// Check if the current request is an add new request and edit mode is
in Template form mode then call the Partialview() to render the
template.
return PartialView("_EditTemplate", new TestModel());
}
else
{
return modelList.GridActions<TestModel>();
} }

5.44 How to: Check which column is filtered in the


OnActionSuccess Client-Side event.
You can follow these steps to check the filtered columns using the “OnActionSuccess” Client-Side
event.
1. Create a Grid control in the view page and configure its properties.
2. In the view page, add the “OnActionSuccess” client side event.

View[cshtml]
@{Html.Syncfusion().Grid<Order>("Filter_Grid")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID").AllowFilter(true)
.Width(100);
column.Add(p => p.EmployeeID).HeaderText("Employee ID").Width(110);
column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(140);
column.Add(P => P.ShipCountry).HeaderText("Ship Country").Width(120);
column.Add(p => p.ShipName);
column.Add(p => p.OrderDate).HeaderText("Order Date")
.Format("{OrderDate:MM/dd/yyyy}").Width(150);

© 2014 Syncfusion. All rights reserved. 1074 | Page


Essential Grid for ASP.NET MVC Classic

})
.EnablePaging()
.EnableFiltering()
.ClientSideEvents(eve => eve.OnActionSuccess("ActionSuccess"))
.AutoFormat(Skins.Marble)
.Render();
}

2. You can get the “CurrentFilterColumn” members from “FilteringMgr” as shown in the following
code example.

[Java Script]
<script type="text/javascript">
function ActionSuccess(sender, args) {
if (args.RequestType == "Filtering") {
var CurrentFilterColumn =
sender.FilteringMgr.get_CurrentFilterColumn().Member;
alert(CurrentFilterColumn + " column filtered");
}
}
</script>

5.45 How to: Use waiting popup of grid, in Client-Side


event of the grid in toolbar button?
You can follow these steps to use waiting popup of grid, in Client-Side event of the grid in toolbar
button.
1. Create a Grid control in the view page and configure its properties.
2. Use “OnLoad” Client-Side event and refresh the Grid using sendRefreshRequest method of
Grid’s Object to initiate the waiting popup.
3. Use Client-Side event “OnToolbarClickEvent” and show the waiting pop up by calling
“ShowPopUp” method before making any ajax call in it. After the ajax call is completed, hide the
waiting popup by calling “HidePopUp” method.

[cshtml]
@{Html.Grid<Editing.Models.EditableOrder>("Grid1")
.Datasource((IEnumerable<Editing.Models.EditableOrder>)ViewData["data"]
)
.Column(column =>

© 2014 Syncfusion. All rights reserved. 1075 | Page


Essential Grid for ASP.NET MVC Classic

{
column.Add(p => p.OrderID).HeaderText("Order
ID").Width(100).TextAlign(TextAlignment.Right);
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.EmployeeID).HeaderText("Employee
ID").TextAlign(TextAlignment.Right).Width(110);
column.Add(p => p.ShipName).HeaderText("Ship Name");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
})
.ClientSideEvents(e => e.OnToolbarClickEvent("OnToolbarClickEvent")
.OnLoad("Load"))
.ToolBar(tools =>
{
tools.Add("Expand", "ExpandItem")
.Add("Collapse", "CollapseItem")
.Add("Refresh", "RefreshItem")
}).Render();}

[script]

function Load(sender) {
$find('Grid1').sendRefreshRequest();
}
function OnToolbarClickEvent(sender, args) {
gridObj = sender;
if (args._currentItemIndex == 0) {
sender._waiting.ShowPopUp();
$.ajax({
type: "POST",
url: "Home/AjxCall"
}).done(function () {
sender._waiting.HidePopUp();
});
}

© 2014 Syncfusion. All rights reserved. 1076 | Page


Essential Grid for ASP.NET MVC Classic

. .. }

5.46 How to: Add a hyperlink to unbound Column of


MVC Grid
You can follow these steps to add a hyperlink to unbound Column of MVC Grid,
1. Create a Grid control in the view page and configure its properties.
2. Add Commands to the grid columns, with the required CommandTypes and then set the
ItemType as "HyperLink"(which is of typr “UnBoundItem”).

Refer the following code example:


View [cshtml]

@(Html.Syncfusion().Grid<EditableOrder>("SampleGrid")
.Datasource((IEnumerable<EditableOrder>)ViewData["data"])
.EnablePaging()
.ActionMode(ActionMode.JSON)
.EnableSorting()
.Caption("Orders")
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.EmployeeID).HeaderText("EmployeeID");
column.Add(c => c.ShipCountry).HeaderText("Ship Country");
column.Add(c => c.ShipCity).HeaderText("Ship City");
column.Add("ManageRecords", col =>
{
// Unbound column for editing records.
col.Commands(cmd =>
{
cmd.Command(CommandTypes.Edit).Text("Edit")
.ItemType(UnBoundItemTypes.HyperLink).ItemOption(UnboundItemOptions.Tex
tOnly);
});
// Unbound column for updating records.

© 2014 Syncfusion. All rights reserved. 1077 | Page


Essential Grid for ASP.NET MVC Classic

col.Commands(cmd =>
{
cmd.Command(CommandTypes.Update).Text("Update").ItemType(UnBoundItemTyp
es.HyperLink)
.ItemOption(UnboundItemOptions.TextOnly);
});
}).UnBound(true); // Unbound is set to true to enable unbound column
})
.Mappers(mapper=>{
mapper.InsertAction("AddOrder").SaveAction("OrderSave").DeleteAction("D
eleteOrder");
})
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})

.Editing(edit =>
{
edit.AllowEdit(true).AllowNew(true).AllowDelete(true);

edit.PrimaryKey(key => key.Add(p => p.OrderID));})


)

5.47 How to: Remove up and down arrows in numeric


textbox
You can follow these steps to remove up and down arrows in numeric textbox,
1. Create a Grid control in the view page and configure its properties.
2. Enable editing using Editing method and configure its properties (AllowNew, AllowEdit and
AllowDelete.)
3.To disable the up and down arrows in numeric textbox through view page, set the
.ShowSpinButton() to “false”.

© 2014 Syncfusion. All rights reserved. 1078 | Page


Essential Grid for ASP.NET MVC Classic

View[cshtml]

@(Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Caption("Orders")
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID").Width(100);
column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(100);
column.Add(p => p.EmployeeID).NumericEditParams(e=>
e.ShowSpinButton(false));
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
})
.EnablePaging()
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})
.Mappers(mapper =>
{
mapper.InsertAction("AddOrder")
.SaveAction("OrderSave")
.DeleteAction("DeleteOrder");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);

© 2014 Syncfusion. All rights reserved. 1079 | Page


Essential Grid for ASP.NET MVC Classic

edit.EditMode(GridEditMode.Normal);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
}))

5.48 How to: Set grouping initially with datatable


elements
Essential Grid allows to add column grouping initially by using GroupDescriptors() as illustrated in
the following code example.

View [cshtml]

@(Html.Syncfusion().Grid<System.Data.DataRow>("OrdersGrid")

.Datasource(Model)

.Caption("Orders")

.Column(col =>

col.Add("OrderID", false).HeaderText("Order
ID").TextAlign(TextAlignment.Right);

col.Add("RequiredDate", false).HeaderText("Required
Date").Format("{0:MM/dd/yyyy}");

col.Add("Freight", false).Format("{0:C}").Width(100);

col.Add("ShipName", false).HeaderText("Ship Name").Width(180);

col.Add("ShipCountry", false).HeaderText("Ship Country");

})

.EnablePaging()

.EnableGrouping()

.Grouping(g => g.GroupDescriptors(group => group.Add(new string[] {


"ShipName" })))

© 2014 Syncfusion. All rights reserved. 1080 | Page


Essential Grid for ASP.NET MVC Classic

5.49 How to: Apply manual filtering to the grid with


Queryparam
You can follow these steps to apply manual filtering to the grid with Queryparam.
1. Create a Grid control in the view page and configure its properties.
2. You have to render or create a Textbox and click Submit button in the Html.BeginForm for
manual filtering.
View[cshtml]

@{Html.Syncfusion().Grid<EditableOrder>("Users_Grid")
.Datasource(Model)
.ShowCaption(true)
.Caption("Total")
.Column(column =>
{
column.Add(c => c.OrderID).AllowEditing(false);
column.Add(c => c.EmployeeID);
column.Add(c => c.ShipName);
column.Add(c => c.ShipCity);
column.Add(c => c.ShipCountry);
})
.PageSettings(p => p.AllowPaging(true).PageSize(10))
.QueryParam("?EmpID=" + ViewData["value"])
.AutoFormat(Skins.Marble)
.Render();
}
</div>
@{ using (Html.BeginForm("Index", "Home", FormMethod.Get))
{
<p>Enter Employee ID: </p>
@Html.TextBox("EmpID")
<input type="submit" value="submit" id="sub" />
}}

© 2014 Syncfusion. All rights reserved. 1081 | Page


Essential Grid for ASP.NET MVC Classic

3. When Submit button is clicked, it passes the EmpID value to the controller’s get action, filters
the data, and returns the values to view.

[Controller]

public ActionResult Index(int? EmpID)


{
ViewData["value"] = EmpID;
IEnumerable data;
if (ViewData["value"] != null)
{
data = OrderRepository.GetAllRecords().Take(100).Where(r =>
r.EmployeeID == EmpID).ToList();
}
else
{
data = OrderRepository.GetAllRecords().Take(100).ToList();
}
return View(data);
}

4. In the post action, you can get the EmpID value from the “QueryParam” and using this value,
you can maintain filtering state after any grid actions.
[AcceptVerbs(HttpVerbs.Post)]

public ActionResult Index(PagingParams args, int? EmpID)


{
ViewData["value"] = EmpID;
IEnumerable data;
if (ViewData["value"] != null)
{
data = OrderRepository.GetAllRecords().Take(100).Where(r =>
r.EmployeeID == EmpID).ToList();
}
else

© 2014 Syncfusion. All rights reserved. 1082 | Page


Essential Grid for ASP.NET MVC Classic

{
data = OrderRepository.GetAllRecords().Take(100).ToList();
}
return data.GridActions<EditableOrder>();
}

5.50 How to: Avoid the duplicate row insertion and


display error message
You can follow these steps to avoid duplicate row insertion.
1. Create a Grid control in the view and configure its properties.
View [cshtml]

@(Html.Syncfusion().Grid<EditableOrder>("Grid1")
.Datasource(Model)
.Column(column =>
{
column.Add(p=> p.OrderID).HeaderText("Order
ID").TextAlign(TextAlignment.Right).Width(100);
column.Add(p => p.CustomerID).HeaderText("Customer ID").Width(100);
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("Ship City");
column.Add(p=>p.Freight).HeaderText("Freight").Format("{0:C}")
.TextAlign(TextAlignment.Right)
.Width(100);
})
.EnablePaging()
.ToolBar(tools =>
{
tools.Add(GridToolBarItems.AddNew)
.Add(GridToolBarItems.Edit)
.Add(GridToolBarItems.Delete)
.Add(GridToolBarItems.Update)
.Add(GridToolBarItems.Cancel);
})

© 2014 Syncfusion. All rights reserved. 1083 | Page


Essential Grid for ASP.NET MVC Classic

.Mappers(mapper =>
{
mapper.InsertAction("AddOrder")
.SaveAction("OrderSave")
.DeleteAction("DeleteOrder");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.Normal);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
}))

2. You need to check for duplicate records in the controller mapper action method, if the record
already exists in the grid then add the error message in the response header.
[Controller]

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult AddOrder(EditableOrder ord)
{
Var add =
OrderRepository.GetAllRecords().Where(o=>o.OrderID==ord.OrderID).
FirstOrDefault();
if (add == null)
{
OrderRepository.Add(ord);
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
else
{
string status = string.Empty;
status = "Duplicate Row cannot inserted";

© 2014 Syncfusion. All rights reserved. 1084 | Page


Essential Grid for ASP.NET MVC Classic

Response.AddHeader("Status", status);
var data = OrderRepository.GetAllRecords();
return data.GridActions<EditableOrder>();
}
}

3. The error is passed from controller to view by using ajaxSuccess() method and displays on
the view page.

View [cshtml]

<div>Editing Status:</div><div class="Status" style="color:Red;">


</div>
<script type="text/javascript">
$("#Grid1").ajaxSuccess(function (evt, request, settings) {
$('.Status').html(request.getResponseHeader("Status"));
});
</script>

5.51 How to: Import an Excel(.xlsx) file into Grid


You can follow these steps to import an excel file into grid.
1. You can import Excel file into the Grid using the conversion of the spreadsheet to Datatable as
shown in the following code example.
[Controller]

private DataTable ExcelData()


{
//Step 1 : Instantiate the spreadsheet creation engine.
ExcelEngine excelEngine = new ExcelEngine();

//Step 2 : Instantiate the excel application object.


IApplication application = excelEngine.Excel;

//Open an existing spreadsheet which will be used as a template for

© 2014 Syncfusion. All rights reserved. 1085 | Page


Essential Grid for ASP.NET MVC Classic

generating the new spreadsheet.


//After opening, the workbook object represents the complete in-memory
object model of the template spreadsheet.
IWorkbook workbook =
application.Workbooks.Open(Request.PhysicalApplicationPath +
"/Content/Hotlist.xlsx");
//The first worksheet object in the worksheets collection is accessed.
IWorksheet sheet = workbook.Worksheets[0];
//Read data from spreadsheet.
DataTable customersTable = sheet.ExportDataTable(sheet.UsedRange,
ExcelExportDataTableOptions.ColumnNames);
return customersTable;
}

2. Set the ExcelData() as data source and render the view.

[Controller]
public ActionResult Index()
{
return View(ExcelData());
}

View[cshtml]

@model System.Data.DataTable

@{Html.Syncfusion().Grid<System.Data.DataRow>("Users_Grid")
.Datasource(Model)
.Caption("Users")
.EnablePaging()
.EnableSorting()
.Render();
}

3. To make it work with paging and sorting actions, create a Post method for Index actions and
bind the data source to the grid as illustrated in the following code example.

© 2014 Syncfusion. All rights reserved. 1086 | Page


Essential Grid for ASP.NET MVC Classic

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)
{
return ExcelData().AsEnumerable().GridActions<System.Data.DataRow>();
}

5.52 How to: Load only required rows from database,


instead of loading all data.
You can achieve this by using Custom Data Binding (“EnableOnDemand”) in MVC grid. Refer the
following link for a demo of Custom Data Binding.

Online link : http://mvc.syncfusion.com/demos/ui/grid/DataBinding/CustomBinding

5.53 How to: Enum Dropdown in grid


Setting Enum values to DropDownlist can be achieved by converting it into list and passing
IEnumerable list values to the DropDownlist.

[Controller]

public List<SelectListItem> InvestigationList


{
get
{
var data =
Enum.GetValues(typeof(InvestigationActionType)).Cast<InvestigationActio
nType>()
.Select(v => new SelectListItem
{
Text = v.ToString(),
Value = v.ToString()
}).ToList();
return data;
}
}
public enum InvestigationActionType

© 2014 Syncfusion. All rights reserved. 1087 | Page


Essential Grid for ASP.NET MVC Classic

{
Created,
Commented,
UploadedFile
}
public ActionResult Index()
{
ViewData["data"] = OrderRepository.GetAllRecords();
ViewData["ShipCountry"] = this.InvestigationList;
return View();
}

View [Cshtml]

@(Html.DropDownListFor(model=>model.ShipCountry,(IEnumerable<SelectList
Item>)

ViewData["ShipCountry"])
)

5.54 How to: Store the Grouping, Sorting, Filtering and


Columns Info in XML
You can follow these steps to store the Grouping, Sorting, Filtering and Columns Info in XML.
1. From the Grid’s post action get the Sorting and Filtering information and save it.

[Controller]

[AcceptVerbs(HttpVerbs.Get)]
public ActionResult Index()
{
var data = new NorthwindDataContext().Orders.ToList();
return View(data);
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args)

© 2014 Syncfusion. All rights reserved. 1088 | Page


Essential Grid for ASP.NET MVC Classic

{
IEnumerable data = new NorthwindDataContext().Orders.ToList();
ActionResult result = data.GridActions<Order>();
object sort = args.SortDescriptors; // sort descriptor values
object filter = args.FilterDescriptors; // filter descriptor values
if (args.RequestType == 2)
{
System.Xml.Serialization.XmlSerializer Serialize = new
System.Xml.Serialization.XmlSerializer(sort.GetType());
XmlTextWriter XmlFilter = new
XmlTextWriter(HttpContext.Server.MapPath("SortingFilterInfoXml.xml"),
System.Text.Encoding.UTF8);
XmlFilter.Formatting = System.Xml.Formatting.Indented;
Serialize.Serialize(XmlFilter, sort);
XmlFilter.Close();
}
else if (args.RequestType == 7 && filter != null)
{
System.Xml.Serialization.XmlSerializer Serialize = new
System.Xml.Serialization.XmlSerializer(filter.GetType());
XmlTextWriter XmlFilter = new
XmlTextWriter(HttpContext.Server.MapPath("SortingFilterInfoXml.xml"),
System.Text.Encoding.UTF8); // stored in XML
XmlFilter.Formatting = System.Xml.Formatting.Indented;
Serialize.Serialize(XmlFilter, filter);
XmlFilter.Close();
}
return result;
}

2. Get Grouping and Column information by sending ajax partial post.

View [cshtml]

<p>Click ColumnInfo to get Grouping and Column Order Info</p>


<input id="Group" type="button" name="ColumnInfo" value="ColumnInfo" />

© 2014 Syncfusion. All rights reserved. 1089 | Page


Essential Grid for ASP.NET MVC Classic

[JavaScript]

<script type="text/javascript">
$(function () {
$("#Group").click(function () {
var gridObj = $find("Grid");
var visibleColumns = new Array();
$.each(gridObj.get_VisibleColumns(), function (j, value) {
visibleColumns.push(value.Name);
});
$.ajax({
type: 'post',
url: "Home/Group",
traditional: true,
dataType:'json',
data: { "GroupedColumns": gridObj.get_GroupedColumns(), "VisibleColumns":
visibleColumns }, // Pass Groupedcolumns and Visiblecolumns data
success: function (data) {
alert("Success");
}
});
});
});
</script>

3. Create an XML document. Update the grouping and column values as shown in the following
code example.

[Controller]

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Group(PagingParams args, IEnumerable<string> GroupedColumns,
IEnumerable<string> VisibleColumns)
{
IEnumerable data = new NorthwindDataContext().Orders.ToList();

© 2014 Syncfusion. All rights reserved. 1090 | Page


Essential Grid for ASP.NET MVC Classic

XmlDocument xmlDoc = new XmlDocument();


XmlElement ColumnInfo = xmlDoc.CreateElement("ColumnInfo");
xmlDoc.AppendChild(ColumnInfo);
XmlElement groupElements = xmlDoc.CreateElement("GroupedColumns");
ColumnInfo.AppendChild(groupElements);
foreach(var groupColumn in GroupedColumns) // update GroupedColumns
{
XmlElement columnElement = xmlDoc.CreateElement("ColumnName");
columnElement.InnerText = groupColumn.ToString();
groupElements.AppendChild(columnElement);
}
XmlElement VisibleElements = xmlDoc.CreateElement("VisibleColumns");
ColumnInfo.AppendChild(VisibleElements);
foreach (var vColumn in VisibleColumns) // update VisibleColumns
{
XmlElement columnElement = xmlDoc.CreateElement("ColumnName");
columnElement.InnerText = vColumn.ToString();
VisibleElements.AppendChild(columnElement);
}
// Save Xml file

xmlDoc.Save(@HttpContext.Server.MapPath("~/GroupingColumnOrderInfo.xml"));
return Json(String.Empty,JsonRequestBehavior.AllowGet);
}

4. The Grid information is stored in XML. The same logic can be used for storing the information
in database too.

5.55 How to: Multiple Grid not showing on JQuery tabs


Unique grid ID should be used for grids inside tabs. This issue can be resolved by passing the
query params to get the grid id dynamically.

View [Tab]
<div id="tabContainer">
<ul>

© 2014 Syncfusion. All rights reserved. 1091 | Page


Essential Grid for ASP.NET MVC Classic

<li><a href="/JqueryTab/GetHomeTab">Tab 0</a></li>


<li><a href="/JqueryTab/GetHomeTab">Tab 1</a></li>
// gridID is passed as Query params
<li><a href="/JqueryTab/Grid?gridid=1">Grid 1 Tab</a></li>
<li><a href="/JqueryTab/GetProductTab">Tab 2</a></li>
<li><a href="/JqueryTab/Grid?gridid=2">Grid Tab</a></li>
</ul>
</div>

View [Grid]
@(Html.Syncfusion().Grid<Tab.Models.Order>((string)ViewData["GridId"])
// Queryparam gridID can get the value from ViewData["GridId"]
.Datasource(Model)
.Caption("Orders")
.AutoFormat(Skins.Marble)
.Column(col =>
{
col.Add(c => c.OrderID).HeaderText("Order ID").Width(60);
col.Add(c => c.EmployeeID).HeaderText("Employee ID").Width(80);
col.Add(c => c.ShipName).HeaderText("Ship Name").Width(300);
col.Add(c => c.ShipCity).Width(175).HeaderText("Ship City").Width(100);
}))

[Controller]

public ActionResult Grid(string gridid)


{
var data = new northwindDataContext().Orders.Take(300);
ViewData["grid"] = data;
if (gridid != null) // GridID is passed to grid View
ViewData["GridId"] = "GridID" + gridid;
return PartialView("Grid");

© 2014 Syncfusion. All rights reserved. 1092 | Page


Essential Grid for ASP.NET MVC Classic

5.56 How to: Preventing Grid focus at the top of grid


Enabling Keyboard Navigation feature focuses the whole grid while clicking on it. You can prevent
focusing the whole grid by setting AllowKeyboardNavigation property to “false”.

View [Cshtml]

@{Html.Syncfusion().Grid<Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID).Width(200).HeaderText("OrderID");
col.Add(c => c.EmployeeID).Width(150).HeaderText("Emp ID");
col.Add(c => c.CustomerID).Width(150);
col.Add(c => c.OrderDate).Width(150);
col.Add(c => c.Freight).Width(150);
})
//Setting keyboard navigation to false.
.AllowKeyboardNavigation(false)
.Render();
}

View [ASPX]

<%= Html.Syncfusion().Grid<Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID).Width(200).HeaderText("OrderID");

© 2014 Syncfusion. All rights reserved. 1093 | Page


Essential Grid for ASP.NET MVC Classic

col.Add(c => c.EmployeeID).Width(150).HeaderText("Emp ID");


col.Add(c => c.CustomerID).Width(150);
col.Add(c => c.OrderDate).Width(150);
col.Add(c => c.Freight).Width(150);
})
//Setting keyboard navigation to false.
.AllowKeyboardNavigation(false)
.Render();
%>

5.57 How to: Programmatically filter a column


You can follow these steps to filter a column programmatically,
1. Create a Grid control in the view and configure its properties. You have to create
“OnActionBegin” client side event and “QueryCellInfo” event. Refer the following code example.

View [Cshtml]
@{Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.EnableFiltering()
.ClientSideEvents(e => e.OnActionBegin("begin"))
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order Date");
column.Add(p => p.Freight).HeaderText("Freight");
})
.QueryCellInfo(
cell => Html.RenderAction("onQueryCellAction", "Home", new
{ args = cell })
)
.EnablePaging()

© 2014 Syncfusion. All rights reserved. 1094 | Page


Essential Grid for ASP.NET MVC Classic

.EnableSorting()
.EnableGrouping()
.AutoFormat(Skins.Sandune)
.Render();
}

View [ASPX]

<%Html.Syncfusion().Grid<Order>("GridSrc")
.Datasource(Model)
.Caption("Order Grid")
.EnableFiltering()
.ClientSideEvents(e => e.OnActionBegin("begin"))
.Column(column =>
{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.EmployeeID).HeaderText("Employee ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.OrderDate).HeaderText("Order Date");
column.Add(p => p.Freight).HeaderText("Freight");
})
.QueryCellInfo(
cell => Html.RenderAction("onQueryCellAction", "Home", new
{ args = cell })
)
.EnablePaging()
.EnableSorting()
.EnableGrouping()
.AutoFormat(Skins.Sandune)
.Render();
%>

2. Button click event is used for programmatic filtering.

© 2014 Syncfusion. All rights reserved. 1095 | Page


Essential Grid for ASP.NET MVC Classic

View [Cshtml]
<input type="text" name="filter" id="filter" />
<input type="button" name="btn" value="filter" onclick="filter()" />

View [Java Script]

<script type="text/javascript">
function begin(sender, args) {
args.data["searchdescriptors"]=
Sys.Serialization.JavaScriptSerializer.serialize(sender._search);
}
function filter() {
var gridobj = $find('GridSrc');
var filterobj = new Array();
var searchText = $('input#filter').val();
var filterObjCustomerID = {};
var filterObjShipCountry = {};
filterObjCustomerID["Column"] = "CustomerID";
filterObjShipCountry["Column"] = "ShipCountry";
filterObjShipCountry["Operator"] = filterObjCustomerID["Operator"] =
"8";
filterObjShipCountry["Value"] = filterObjCustomerID["Value"] =
searchText;
filterObjShipCountry["Predicate"] = filterObjCustomerID["Predicate"] =
"0";
filterObjShipCountry["IsCaseSensitive"]=
filterObjCustomerID["IsCaseSensitive"]= false;
gridobj._search = [];
Array.add(gridobj._search, filterObjCustomerID);
Array.add(gridobj._search, filterObjShipCountry);
gridobj.sendRefreshRequest();
}</script>

3. “QueryHelper” is used for filtering

[Controller]

© 2014 Syncfusion. All rights reserved. 1096 | Page


Essential Grid for ASP.NET MVC Classic

public static class IQueryableHelper


{
Public static List<FilterDescriptor> ConvertObjToFilters(object[]
searchConditions)
{
List<FilterDescriptor> searchList = new
List<FilterDescriptor>();
FilterDescriptor sCondition = null;
searchConditions.ForEach(condition =>
{
sCondition = new FilterDescriptor();
Dictionary<string, object> col = (Dictionary<string, object>)condition;
sCondition.ColumnName = col["Column"].ToString();
sCondition.Operator = (FilterType)Convert.ToInt32(col["Operator"]);
sCondition.Value = (object)col["Value"];
sCondition.Predicate =
(PredicateType)Convert.ToInt32(col["Predicate"]);
if (sCondition.Value!= null && sCondition.Value.ToString() !=
string.Empty)
searchList.Add(sCondition);
sCondition.IsCaseSensitive = Convert.ToBoolean(col["IsCaseSensitive"]);
});
return searchList;
}
public static IQueryable Search(this IQueryable source,
List<FilterDescriptor>

searchConditionCollection)
{
List<FilterDescriptor> searchList = searchConditionCollection.ToList();
IEnumerable<FilterDescriptor> emptyConditions = searchList.Where(c =>
c.Value == null).ToList();

emptyConditions.ForEach(condition =>
{

© 2014 Syncfusion. All rights reserved. 1097 | Page


Essential Grid for ASP.NET MVC Classic

searchList.Remove(condition);
});
IEnumerable<FilterDescriptor> blankConditions = searchList.Where(c =>
c.Value.ToString() == "(Blank)").ToList();

blankConditions.ForEach(condition =>
{
condition.Value = string.Empty;
});
Expression predicate = null;
Expression predicate2 = null;
IEnumerable<IGrouping<string,FilterDescriptor>>filtersgroups=searchList
.GroupBy(f => f.ColumnName);

ParameterExpression paramExpression = source.ElementType.Parameter();


var firstLoop = false;
foreach (IGrouping<string, FilterDescriptor> conditionsGroup in
filtersgroups)
{
var columnName = conditionsGroup.Key;
IEnumerable<FilterDescriptor> searchconditions =
conditionsGroup.Cast<FilterDescriptor>();
foreach (FilterDescriptor condition in searchconditions)
{
if (!firstLoop)
{
predicate2 = source.Predicate(paramExpression, condition.ColumnName,
condition.Value, condition.Operator, condition.IsCaseSensitive,
source.ElementType);
firstLoop = true;
}
else
{
if (condition.Predicate == PredicateType.And)
{
predicate2 = predicate2.AndPredicate(source.Predicate(paramExpression,

© 2014 Syncfusion. All rights reserved. 1098 | Page


Essential Grid for ASP.NET MVC Classic

condition.ColumnName, condition.Value, condition.Operator,


condition.IsCaseSensitive, source.ElementType));
}
else if (condition.Predicate == PredicateType.Or)
{
predicate2 = predicate2.OrPredicate(source.Predicate(paramExpression,
condition.ColumnName, condition.Value, condition.Operator,
condition.IsCaseSensitive, source.ElementType));
}
}
}
if (predicate == null)
{
predicate = predicate2;
}
else
{
predicate = predicate.OrPredicate(predicate2);
}
predicate2 = null;
firstLoop = false;
}
if (paramExpression != null && predicate != null)
{
var lambda = Expression.Lambda(predicate, paramExpression);
return source.Where(paramExpression, predicate);
}
return source;
}}

4. Call the searching function in the Grid post action.

[ASPX]

[Controller]

© 2014 Syncfusion. All rights reserved. 1099 | Page


Essential Grid for ASP.NET MVC Classic

[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args, string searchdescriptors)
{
var engine = data.GridActions<Order>() as GridHtmlActionResult<Order>;
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;
}
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(PagingParams args, string searchdescriptors)
{
object[] searchConditions = new JavaScriptSerializer().Deserialize<
object[]>(searchdescriptors);
IEnumerable data = new NorthwindDataContext().Orders.Take(200);
if (searchConditions != null && searchConditions.Count() > 0)
data=data.AsQueryable().Search(IQueryableHelper.ConvertObjToFilters(sea
rchConditions));
var engine = data.GridActions<Order>() as GridHtmlActionResult<Order>;
engine.GridModel.QueryCellInfo = onQueryCellAction;
return engine;
}

5. After postback, “QueryCellInfo” event handles the events in the controller.

[Controller]

public void onQueryCellAction(GridTableCell<Order> args)


{
if(args.TableCellType==GridTableCellType.RecordFieldCell||args.TableCellType
== GridTableCellType.AlternateRecordFieldCell)

{
if (args.Column.MappingName == "OrderID")
{
args.Text = "<a href='http://www.google.com'>"+args.Data.OrderID +"</a>";
}
}

© 2014 Syncfusion. All rights reserved. 1100 | Page


Essential Grid for ASP.NET MVC Classic

5.58 How to: Set the number of records per page and for
subsequent pages, by default.
You can follow these steps to set the number of records per page by default and in subsequent
pages.
1.Configure the grid with its properties.

View [cshtml]

@{Html.Syncfusion().Grid<EditableOrder>("OrderGrid")
.Column(cols =>
{
cols.Add(c => c.OrderID);
cols.Add(c => c.ShipCity);
cols.Add(c => c.ShipCountry);
cols.Add(c => c.Freight);
cols.Add(c => c.CustomerID);
})
.ClientSideEvents(events=>events.OnActionBegin("BeginAction"))
.EnablePaging()
.PageSettings(page => page.AllowPaging(true)
.PageSize(10)
.PagerStyle(PagerStyle.Default))
}

2. You can do this manually, by changing the PageSize according to the current page number in
“OnActionBegin” Client-Side events as shown in the following code example.

© 2014 Syncfusion. All rights reserved. 1101 | Page


Essential Grid for ASP.NET MVC Classic

[JavaScript]

<script type="text/javascript">
function BeginAction(sender, args) {
var gridObj = $find('OrderGrid');
var pageNumber = parseInt(gridObj._pager._currentPageNo);
var clientobject =
Sys.Serialization.JavaScriptSerializer.deserialize(args.data.ClientObject);
switch (pageNumber) {
case 1:
clientobject["PageSize"] = 10;
break
case 2:
clientobject["PageSize"] = 5;
break;
case 3:
clientobject["PageSize"] = 25;
break;
case 4:
clientobject["PageSize"] = 100;
break;
}
args.data.ClientObject=Sys.Serialization.JavaScriptSerializer.serialize(clientobject);
}
</script>

5.59 How to: Set Image Column using Url.Content


1. Configure grid and its properties. An image in unbound column can be rendered using
Url.Content() as shown in the following code example.

View [cshtml]

@(Html.Syncfusion().Grid<JSONOrder>("UnBoundColumn_Grid")
.Datasource(Model)
.ActionMode(ActionMode.Server)
.Column(column =>

© 2014 Syncfusion. All rights reserved. 1102 | Page


Essential Grid for ASP.NET MVC Classic

{
column.Add(p => p.OrderID).HeaderText("Order ID");
column.Add(p => p.CustomerID).HeaderText("Customer ID");
column.Add(p => p.ShipCountry).HeaderText("Ship Country");
column.Add(p => p.ShipCity).HeaderText("ShipCity");
column.Add(p=>p.OrderDate).HeaderText("OrderDate").Format("{OrderDate:MM/dd/yyyy}");
column.Add("Image").HeaderText("Image").Format("<img src='" +
@Url.Content("~/Content/{EmployeeID}.png") + "'/>").UnBound(true);
}))

5.60 How to: Bind Javascript onkeypress event on


editcell
In the DialogEdit of grid, binding the Client-Side “OnKeypress” event can be done by handling
Client-Side “OnActionSuccess” event. Find the input of the Column to which the Keypress event
needs to be fired and then bind the keypress event to it. Configure the grid with its properties and
events as shown in the following example.
View [cshtml]

@{Html.Syncfusion().Grid<Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);
col.Add(c => c.CustomerID).HeaderText("CustID");
col.Add(c => c.Freight);
})
.ClientSideEvents(events =>
{
events.OnActionSuccess("complete");
})
.Editing(edit =>
{
edit.AllowEdit(true)

© 2014 Syncfusion. All rights reserved. 1103 | Page


Essential Grid for ASP.NET MVC Classic

.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.Dialog);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
.Render();
}

[JavaScript]

<script type="text/javascript">
function complete(sender, args) {
var grid = $("#SampleGrid_EditDialog").find('#SampleGridFreight').keypress(
function (evt) { // SampleGrid is Grid ID and Freight is the column which is
need to bind keypress event.
alert('KeyPress event fired');
});
}
</script>

5.61 How to: Click automation of the edit dialog save


button
Automating the click event of Save button in Dialog edit can be achieved by binding “Keypress”
Client-Side event by handling “OnActionSuccess” of Grid. Configure grid with its properties and
events as shown in the following code example.
View [cshtml]

@{Html.Syncfusion().Grid<Order>("SampleGrid")
.Datasource(Model)
.Caption("Orders")
.Column(col =>
{
col.Add(c => c.OrderID);
col.Add(c => c.EmployeeID);

© 2014 Syncfusion. All rights reserved. 1104 | Page


Essential Grid for ASP.NET MVC Classic

col.Add(c => c.CustomerID);


col.Add(c => c.Freight);
})
.ClientSideEvents(events =>
{
events.OnActionSuccess("complete");
})
.Mappers(mapper=>{
mapper.SaveAction("OrderSave")
.InsertAction("AddOrder")
.DeleteAction("DeleteOrder");
})
.Editing(edit =>
{
edit.AllowEdit(true)
.AllowNew(true)
.AllowDelete(true);
edit.EditMode(GridEditMode.Dialog);
edit.PrimaryKey(key => key.Add(p => p.OrderID));
})
}

[JavaScript]

function complete(sender, args) {


//”SampleGrid” is the Grid ID
var grid = $("#SampleGrid_EditDialog").keypress(function (evt) {
if (evt.keyCode == 13) {
sender.sendSaveRequest();
}
});
}

© 2014 Syncfusion. All rights reserved. 1105 | Page


Essential Grid for ASP.NET MVC Classic

5.62 How to: Use AntiForgeryToken with Grid Editing


For using grid with “AntiForgeryToken”, you have to pass token value to controller with grid
params. When any event occurs from grid, the grid parameters passes through AJAX post
checks the token value of “ValidateAntiForgeryToken” in the controller. It throws the following
exception/error [“A required antiforgery token was not supplied or invalid”] because token value
for validaton is not available in Grid params. You can resolve this issue by passing token value
with grid params using “OnActionBegin“ event.

[Aspx]

@(Html.Syncfusion().Grid<EditableOrder>("SampleGrid")
.Datasource((IEnumerable<EditableOrder>)ViewData["data"])
.ActionMode(ActionMode.Server)
.Column(column =>
{
column.Add(c => c.OrderID).HeaderText("Order ID");
column.Add(c => c.OrderDate).HeaderText("Order Date");
column.Add(c => c.ShipCity).HeaderText("Ship City");
})
.ClientSideEvents(
evt => evt.OnActionBegin("Begin")
)
)

[JavaScript]

function Begin(sender, args) {


var clientobject = args.data;
clientobject["__RequestVerificationToken"] =
$("[name='__RequestVerificationToken']").val();
args.data = clientobject;
}

© 2014 Syncfusion. All rights reserved. 1106 | Page


Essential Grid for ASP.NET MVC Classic

© 2014 Syncfusion. All rights reserved. 1107 | Page


Essential Grid for ASP.NET MVC Classic

Adding Template to the Grid Column in an


Index Application 833
Adding the Filter Bar to an MVC Grid 224
Adding the Grid Toolbar in an Application 841
A
Adding Word Export to MVC Grid 489
Action mapper 87
AddNew Request 828
Action Mapper with text and value field 96
ADO.NET Entity Model Data Source 53
Action Modes 39
Appearance 424, 647, 743, 857, 994
Add StyleManager and ScriptManager 958, 974,
989 Appearance and Structure of PDF Export 480
Adding a Model to the Application 927 Appearance and Structure of the Word Export 486
Adding Codes to the Views Web.config file Arguments details for the ClientSide events. 781
(Views\Web.config) 974, 988
Auto Wrap-Up of Column Cells 743
Adding Codes to the Web.config File 956, 971,
AutoFormatting Class 464
986
AutoFormatting Repository 465
Adding Editing-Rows 339
Auto-Generated Columns 114
Adding Essential Grid to the Application Using
Razor 965 B
Adding Essential Grid to the Application Using Bind drop-down data using Action Mapper 87
ASPX 950
Bind drop-down data using Array 105
Adding Essential Grid to the Simple Razor
Bind drop-down data using the Enumerable
Application using VB 981
method 70
Adding Essential MultiColumnDropDown to an
Built-in Context Menu Items 621
Application 851
Built-in Skin Styles 647
Adding Grid to the project 35
By ColumnIndex 799
Adding Handlers 774
By ColumnName 798
Adding Handlers through Builder 891
C
Adding Handlers through
MultiColumnDropDownModel 893 Cancel Request 829
Adding Keyboard Interface Support to an CellEditType 351
Application 610
Clear Sorting 820
Adding Localization to an Application 668
Client-Side Events 637, 887
Adding Merge Cells to an Application 718
Client-Side Events and Methods 751
Adding PDF Export Support to MVC Grid 483
Client-Side Interactivity 1006
Adding Reference Assemblies 950, 966, 982,
Client-Side Methods 894
1009
Clone element of a dragged column 818
Adding ScriptManager 959, 975, 989, 1017
Code samples 923
Adding Scripts 953, 968, 983, 1011
Column 798
Adding StyleManager 958, 974, 989, 1016

© 2014 Syncfusion. All rights reserved. 1108 | Page


Essential Grid for ASP.NET MVC Classic

Column Formatting 506 Customizing the Grid Toolbar in an Application


841
Column Mapping 881
D
Column Templates 833
Data Binding 48, 853
Concepts and Features 39, 853
Data binding support 70
Conditional Formating 537
Data binding support for drop-down lists in
Configure the root Web.config file 1014
columns 68
Configuring an editing-row 340
DataTable Support 143
Configuring CellEditType 351
Default Deployment Pattern 24
Configuring the Default Keys 613
Defining the Display Conditions 877
Configuring the Views Web.config
Delete Request 829
(Views\Web.config) 1016
Deployment Requirements 23
Context Menu 621
Dialog editing in MVC Grid 380
Converting an existing MVC application to a
Syncfusion MVC application 33 Direction for the Enter key 789
Create the ADO.NET Entity Data Model 935 Direction for the Tab key 790
Create the Generic Collection Model 940 Disable Editing in Specified Columns 280
Create the Grid using view customization with DLL 24
Default view 943
Documentation 21
Creating a Platform Application 945
Drag Any Other Element and Drop into Grid 599
Creating a Strongly Typed View 932
Drag and Drop 592
Creating a Strongly Typed View Manually 934
Drag-and-Drop Support 1006
Creating an MVC4 Razor application with the
Dragging and Dropping Grid Rows into Any Other
Syncfusion Project Template 29
Element 592
Creating the Grid control 959, 975
Dynamic Data Binding 136
Creating the Grid Control in the View 990, 1017
Dynamically Bind Data to Grid without mapping to
Current Cell 793, 814 column names 136
Current Page 787 Dynamically Bind data with mapping the column
name as string 139
Current Selected Area 815
E
Current Selected Column Header 817
Edit Mode Configuration 397
Current Selected Row Header 816
Editable and Repository class details 459
Custom Binding 116
EditableOrder Class 459
Custom Formatting 512
Editing 254, 688, 997
Customization 672, 676
Editing functionality 806
Customizing the Context Menu 637
Editing Request 828
Customizing the Grid Appearance 652
Elaborate Structure of MultiColumnDropDown 850
Customizing the Grid Pager in an Application 170

© 2014 Syncfusion. All rights reserved. 1109 | Page


Essential Grid for ASP.NET MVC Classic

Elaborate Structure of the Control 992 Formatting 505


Elements and Features 993 Formatting Data 1002
Enable/Disable Methods 804 Freezing Grid Rows/Columns in an Application
733
Enabling Auto Wrap-Up in Grid MVC 747
Freezing Panes 740
Enabling Dialog Editing in MVC Grid 384
Freezing Rows and Columns 732
Enabling Excel-Like Editing in MVC Grid 369
G
Enabling External Form Edit Mode in Grid MVC
410 Generic Collections 58
Enabling Keyboard Interface with Default Keys Getting Started 29
610
Getting Started with the Syncfusion MVC Grid 29
Enabling Stacked Headers in Grid MVC 710
Grid EditMode Configuration 269, 290, 310, 328
Enabling Unbound Column Editing in MVC Grid
Grid preparation 149
425
GridPropertiesModel Table 846
Entire Grid 795
Group Column 821
Enumerable data 70
GroupDropArea 801
Enumerable data with text and value field 78
Grouping 237, 994
Events 495, 849
Grouping Customization 242, 246, 250, 254
Excel Export 468
Grouping functionality 808
Excel Export Request 827
Grouping Methods 821
Excel-Like Editing in MVC Grid 366
Grouping Request 826
Expand/Collapse Grouped column 784
H
Exporting 468, 1000
Hiding Row Header in Grid 1035
Exporting through Custom Buttons 476
Hierarchical Grid 678
External Form Edit Mode 407
How do I Add Essential Grid to the Simple MVC 4
F
Razor Application? 1009
Facebook Mode 579
How to 927
Fast Deployment Pattern 24
How to avoid Grid Invisibility 1019
Feature Summary 993
How to create and assign columns to a grid in the
Filter Bar 221 controller through the grid-properties model
1023
Filter Customization 205, 211, 215, 220
How to Filter Data Using Filter Tokens in the Filter
Filter Tokens 223
Bar 230
Filtering 197, 996
How to Format Cells and Rows in a Grid that Was
Filtering in the MultiColumnDropDown Control 913 Exported to PDF 495
Filtering Request 825 How to manually configure the MVC application for
Grid 945
For PDF 495
For Word 500

© 2014 Syncfusion. All rights reserved. 1110 | Page


Essential Grid for ASP.NET MVC Classic

How to send the request to the Grid using External How to: Enum Dropdown in grid 1087
Button 824
How to: Format the cells through QueryCellInfo
How to Use Other Controls Inside the event 1045
DialogEditorTemplate? 1023
How to: Format the Grid columns 1035
How to: Get custom theme for multiple (Grid,
How to: Format the values in the filter dialog. 1054
Tools, Schedule) controlsHow to: Move Grid
rows Up and Down using Button 1047 How to: Get selected records in another view 1039
How to: Get properties of the grid 1039 How to: Get the selected row values in
ToolbarClick event 1029
How to: overcome “Check whether the grid post
action is defined in controller” error when How to: Hide columns when exporting Grid 1036
editing 1032
How to: Hide filter icon in grid table header 1049
How to: Refresh grid contents on external button
How to: Hide GroupHeaderArea when Grouping is
click 1028
defined in code 1063
How to: Resolve Database configuration error
How to: Hide MasterCellCollapse/Expand in
1027
Hierarchy Grid 1062
How to: Add a hyperlink to unbound Column of
How to: Import an Excel(.xlsx) file into Grid 1085
MVC Grid 1077
How to: Load only required rows from database,
How to: Add New, Delete and Update multiple
instead of loading all data. 1087
grids uing external button 1055
How to: Multiple Grid not showing on JQuery tabs
How to: Apply manual filtering to the grid with
1091
Queryparam 1081
How to: overcome “Registering style sheet for the
How to: Assign datasource for a DropdownEdit at
Grid failed because assembly does not exist”
clientside 1064
error 1026
How to: Avoid the duplicate row insertion and
How to: Preventing Grid focus at the top of grid
display error message 1083
1093
How to: Avoid validation messages invisibility
How to: Programmatically filter a column 1094
1028
How to: Remove up and down arrows in numeric
How to: Bind Javascript onkeypress event on
textbox 1078
editcell 1103
How to: Right align summary row values 1053
How to: Change dropdown to textbox cell for
particular cells when celledit type is dropdown How to: Save the Grid Content using an External
1060 Button. 1060
How to: Change entire column values in client How to: Set Grid height and width in Client-Side
side. 1068 1031
How to: Check which column is filtered in the How to: Set grouping initially with datatable
OnActionSuccess Client-Side event. 1074 elements 1080
How to: Click automation of the edit dialog save How to: Set Image Column using Url.Content 1102
button 1104
How to: Set the height of the grid rows 1050
How to: Custom server paging with initial grouping
How to: Set the number of records per page and
1051
for subsequent pages, by default. 1101
How to: Disable sorting for specific columns in
How to: Show tooltip on Grid Cell MouseHover in
Grid 1038
JSON mode 1043

© 2014 Syncfusion. All rights reserved. 1111 | Page


Essential Grid for ASP.NET MVC Classic

How to: Show tooltip on Grid Cell MouseHover in O


Server mode 1042
OrderDetailEdit Class 466
How to: Store the Grouping, Sorting, Filtering and
OrderDetailRepository 466
Columns Info in XML 1088
OrderRepository Class 461
How to: Update the cell value at client side 1067
Overview 18
How to: Use alternate row color background 1053
P
How to: Use AntiForgeryToken with Grid Editing
1106 Page Size 788
How to: Use one column data value in another Pager customization 158, 162, 165, 168, 169
column 1050
Paging 154, 996
How to: Use waiting popup of grid, in Client-Side
Paging functionality 810
event of the grid in toolbar button? 1075
Paging Request 825
HTML Action Request 830
Passing Values between Grid Actions 831
I
PDF Export 480
Installation and Deployment 23
PDF Export Request 827
Integrating the Grid and Knockout’s ViewModel
151 Playing with the JSON Collection 152
Introduction to Essential Grid for ASP.NET MVC Prerequisites and Compatibility 20
18
Primary key collection 786
J
Project Migration Utility 33
JSON Binding to MVC Grid and Monitoring
Project Template Utility 29
Changes with Knockout.js 149
Properties 69, 222, 339, 409, 492, 744
JSON Mode 44, 163, 187, 213, 247, 301, 442,
521, 532, 558, 681, 697, 725, 837, 902, 921 Properties and Events Tables 381
JSONOrder Class 463 Properties Explanation 606
K Properties Tables 422
Keyboard Interface 608 Properties, Methods, and Events 912
Knockout’s ViewModel 150 Property Tables 634
L Property, Method, and Event Tables 634
LINQ to SQL Data Source 49 Q
Localization 667 QueryCellInfo Action 512
M R
Merge Cells 716 Refresh Request 830
Methods 69, 494, 636, 847 Removing Handlers from Grid 783
MultiColumnDropDown 849 ReOrder Columns 823
Multiple rows in a Grid 794 Reorder Method 823
N RightToLeft 863
Normal Mode 573 Row 791, 796

© 2014 Syncfusion. All rights reserved. 1112 | Page


Essential Grid for ASP.NET MVC Classic

RowDataBound Action 526 Through GridBuilder 40, 44, 49, 54, 58, 63, 71, 79,
87, 96, 106, 114, 117, 127, 136, 140, 144,
RowHeader 803
156, 163, 170, 177, 187, 202, 213, 224, 230,
RowHover 804 238, 247, 259, 301, 340, 352, 369, 384, 410,
425, 442, 469, 483, 489, 495, 500, 514, 521,
S
527, 532, 538, 551, 558, 565, 573, 579, 587,
sampleCustomize Methods 814 595, 602, 610, 613, 626, 637, 648, 653, 668,
678, 681, 688, 697, 710, 718, 726, 733, 747,
Samples and Location 25
774, 831, 841, 921, 959, 975
Save Request 829
Through GridProperties model 227, 415, 576
Scrolling 564, 1002
Through GridPropertiesModel 42, 46, 51, 56, 60,
Searching 230 66, 74, 83, 92, 101, 109, 115, 122, 131, 138,
142, 147, 160, 167, 172, 183, 192, 209, 218,
Searching Request 824
234, 243, 251, 282, 320, 345, 358, 375, 391,
Select and Deselect Methods 791 434, 451, 472, 484, 490, 497, 502, 518, 523,
530, 534, 542, 554, 561, 569, 581, 590, 597,
Selection 583
603, 611,615, 630, 643, 650, 660, 673, 713,
Selection functionality 812 723, 730, 736, 749, 779, 832, 844, 961, 977
Server Mode 40, 156, 177, 202, 237, 259, 425, Through MultiColumnDropDownModel 855, 866,
514, 527, 551, 678, 688, 718, 835, 896, 916 884, 899, 908, 918
Set Methods 786 Through MultiDropdownModel 861, 875, 879
Setting the Orientation 872 Toggle Selection 587
Settings for Essential Grid in MVC 4 Application Toolbar 840
930
ToolbarOptions Table 846
Show and Hide Methods 796
U
Sorting 176, 819, 896, 995
Unbound Column 62
Sorting customization 181, 185, 190, 195
Unbound Column Editing 421
Sorting Methods 819
Unbound Column Support 1006
Sorting Request 826
Unfreezing Panes 741
Stacked Headers 706
Ungroup Column 822
Strongly Typed View 932
Using CssClass() 509
Summaries 545, 1001
Using Format() 506
Syncfusion Utilites 29
V
T
Virtual Scrolling in MVC Grid 572
Tables for Properties, Methods, and Events 364,
Virtual Scrolling Mode 573
525, 537, 616, 716
W
Through Builder 854, 860, 864, 873, 877, 882,
896, 902, 916 Web Service Data Binding 127
Through Grid Client Object 780 Word Export 486
Word Export Request 827

© 2014 Syncfusion. All rights reserved. 1113 | Page


Essential Grid for ASP.NET MVC Classic

© 2014 Syncfusion. All rights reserved. 1114 | Page

S-ar putea să vă placă și