Click here to Skip to main content
Click here to Skip to main content

Jquery Grid (VGrid)

, 22 Aug 2014 CPOL
Rate this:
Please Sign up or sign in to vote.
Reusable tool for implementing Grid

 

Introduction

 

VGRID is lightweight, simple to configure, cross-browser compatible grid, built with JQUERY.

In this article we will see to implement the grid in ASP.NET - MVC.

This grid has the following inbuilt features:

  • Header freeze
  • Column visibility setting
  • Column in-line edit and row delete
  • Multiple page selection
  • Customization of column width, table style and title attribute setting
  • Column Resize
  • Column drag and drop and
  • In built blue and black themes
  • Custom Filter

Using the Grid

Road Map

  • Configuring a grid with basic functionality
  • Setting Visibility to a particular column
  • Disabling sorting to a particular column
  • Adding a column with complex association
  • Enabling editing to a particular column
  • Setting the mode of selection to the grid
  • Setting the title to the columns
  • Enabling the MultiPageSelection
  • Enabling the Column-visibility setting Popup
  • Setting colors to the table
  • Configuration for filtering data
  • Event Handler
  • Retrieving the Selected / Updated records
  • Text Align Setting for a particular column
  • Setting the display content for a column
  • Saving records with grid in-built function
  • Enabling the column re-size functionality
  • Enabling the drag and drop functionality
  • Enabling custom filter for the Grid
  • Customizing delete functionality
  • Sample code snippet for the Grid

Configuring a Grid with Basic Functionality

In the page where the grid needs to be implemented, add the following references:

    <!--References -->
    <script type="text/javascript" src="~/VGrid/VGrid.js"/>    
    <link rel="stylesheet" type="text/css" href="~/VGrid/VGrid.css" />    
    <!--Minimum version required-->
    <script src="@Url.Content("~/Scripts/jquery-1.5.1.min.js")" type="text/javascript">;   
    </script>
    <script src="@Url.Content("~/Scripts/jquery-ui-1.8.11.js")" type="text/javascript"></script>
    <!--Add an empty div with unique id-->
    <div id="sampleVGrid">;    < /div>    

In the Script tag or in the referred JavaScript page, add the below code:

        $(document).ready(function(){
$('#sampleVgrid').VGrid({
    header: {
        Name: {
            title: "Student Name",//Column Title
        },
        Id: {
            title: "Student Id"
        },
        'Grade': {    
            title: "Grade",                     
        }
    },
    actions: {
            bindingMethod: "/Vgrid/GetData"            
    },
    pageSize: 10,//Number of records to be displayed per page.Default value is 25. 
    });
});

In server side, add the below code:

[HttpPost]
public JsonResult GetJsonData(string sortDirection, string sortDescription, int pageSize, int startindex)
{
    ///
    ///Server code
    ///
    return Json(new { Records=list,TotalRows=totalRows});
}

Setting Visibility to a Particular Column

Visibility to a particular column can be changed by using the visibility property.

header: {
    Name: {
        title: "Student Name",//Column Title
        visible: false                            
        },
    }
}    

Note: Default value is true.

Disabling Sorting to a Particular Column

Sorting for a particular column can be stopped using the sortable property.

header: {
    Name: {
        title: "Student Name",//Column Title
        sortable: false                            
        },
    }
}

Note: Default value is true.

Adding a Column with Complex Association

header: {
    'Grade': {
        parentClass : 'Academics',//To implement the associated class
        isComplex: true,//To implement the associated class
        title: "Grade",                                   
        }
    }
}

Enabling Editing to a Particular Column

Editing to a particular column can be done by using the editable property. Type of edit can be set by using the editType property. Type of edit are Date time edit , drop down edit and text edit.

Enabling Text Edit

header: {
    'Grade': {
        parentClass : 'Academics',//To implement the associated class
        isComplex: true,//To implement the associated class
        title: "Grade", 
        editable: true,//To make the column editable
        }
    }
}

Enabling Drop down Edit

Action method that provides the source for the dropdown

     actions:{            
            dropDownSourceMethod:'Vgrid/GetDropDownValues'
           }

header: {
   'Grade': {
                parentClass: 'Academics',//To implement the associated class
                isComplex: true,//To implement the associated class
                title: "Grade",
                editable: true,
                editType: 'dropDown',
                dropDownId: 'grade',//Grade is the key provided in the dictionary
                sortable: false
            },
}

Server code for Data source

        /// <summary>
        /// Gets the Drop Down data.
        /// </summary>
        /// <returns>Json Data
        public JsonResult GetDropDownValues()
        {
            try
            {
               var grades = getGrades();
               var standard = getStandard();
               var dict = new Dictionary<string,>>();                
                dict.Add("grade",grades);
                return Json(new{data = dict});
            }
            catch (Exception)
            {                
                throw;
            }
        }

Date time edit

         Dob: {                               
                editable: true,
                editType: "dateTime",
                dateTimeFormat: "dd M yy",
                width:"100px"
            }

Check Box edit

         IsIndian: {                               
                editable: true,
                editType:"checkBox",                
                width:"100px"
            }

Note: Default value is false.

Setting the Mode of Selection to the Grid

Grid can be made selectable by using the selection property. By default, the grid will be non-selectable. It can be made multi select or single select using the selection property.

$('#sampleVgrid').VGrid({
    selection: 'single' // or     selection: 'multiple'
});    

Setting the Title to the Columns

Title attribute to the column can be done using this option. maxLenToDisp is the property to set the value above which the attribute has to be set for the column.

$('#sampleVgrid').VGrid({
    setTitle: true,//Sets the title to the cells value after the specified length
    maxLenToDisp:20,//Sets the title for the cells if the length of the character exceed this value     
});

Enabling the MultiPageSelection

Selection across the pages can be done by using the multiplePageSelection property.

$('#sampleVgrid').VGrid({
    multiplePageSelection:{//Enables the cross page selection
    uniqueIdentifier: 'Id',
    },    
}); 

Enabling the ColumnVisibility setting Popup

Column visibility functionality can be enabled in the grid by using the columnVisibilitySetting property.

$('#sampleVgrid').VGrid({
    columnVisibilitySetting:true    
});

Column visibility popup will be opened by clicking the show-hide button in the info-bar.

Note: Default value is false.

Setting Colors to the Table

Customizing the color of the grid can be done by providing the values against the desired property. The Cell spacing setting is to set the space between the cells:

$('#sampleVgrid').VGrid({
    tableStyle: {
        oddTrColor: '',
            oddTrTextColor:'',
            evenTrColor: '',
            evenTrTextColor:'',
            headerColor: '',
            headerTextColor: '',
            pagerBarColor:'',
            pagerBarTextColor:'',
            columnVisibilitypopColor:'',
            columnVisibilitypopTextColor:'',
            cellSpacing:"1"//Default value is 1
},
});

Configuration for Filtering Data

Filtering the data available in the grid can be done using the onCallStart function.

Add the below code in script:

$('#sampleVgrid').VGrid({
  eventHandlers: {  onCallStart: function (args) {
        //Data to be posted on ajax request
        args['name'] = $('#txtName').val();
        return args;
        }}
});
                
//Button click function        
$('#btnSearch').click(function () {
    gridObject['myNewTable'].load();       
});

//Default load of the grid can be disabled by using the following code
    
$('#sampleVgrid').VGrid({
    defaultLoad:false
});

In server side, add the below code:

    [HttpPost]
public JsonResult GetJsonData(GridParams gridParams){
     ///
     ///Server code 
     ///
     return Json(new { Records=list,TotalRows=totalRows});
}

Note: Variables provided in the args and in the method should be the same.

Event Handler

Ajax post's call back handler

Manipulation of the data can be done using this function. This function will be triggered just before the data is shown in the grid.

$('#sampleVgrid').VGrid({
     eventHandlers: {   
            callBack: function (data) {            
                  //Handler for callback implementations after post
                  ///Logic to manipulate the data                       
                  return data;
             }
        }
});
Selection handler

This function is triggered as soon as the selection is made. It will be useful for selection validations, etc.

$('#sampleVgrid').VGrid({
   eventHandlers: {    
            selectionHandler: function (data) {
                 //Handler for implementation after selection is made
                 return data;
            }
        }
});
Cell save handler

This function will be triggers as soon as the editable cell saves.

$('#sampleVgrid').VGrid({
 eventHandlers: { 
            cellSaveHandler: function (currentCellObj, oldValue, newValue) {                 
                //Do nothing
                return newValue
            }
        } 
});
Save call back handler

This function is the call back handler for save.

$('#sampleVgrid').VGrid({
 eventHandlers: { 
            saveActionCallBack: function (status) {
               if(status=='success')   
                    alert("Saved Successfully");
               if(status=='error')
                    alert("Error in saving");
            },  
});

Retrieving the Selected / Updated Records

The Gridobject retrieves the updated/selected rows as an object which is the data of the row binded with.

//Click function to retrieve the selected records
$('#btnGetSelectedRows').click(function () {
    var  records = gridObject['sampleVgrid'].selectedRecords;    
});

//Click function to retrieve the updated records 
$('#btnGetUpdatedRows').click(function () {
    var records = gridObject['sampleVgrid'].updatedRecords;            
});

Note: Default values for this is undefined (returns default value if no changes have been made or No row has been selected).

Text align setting for a particular column

Text alignment can be made center/Left/Right using the textAlign setting.

        header: {
            Name: {
                title: "Student Name",//Column Title
                textAlign:'center'//Default value is left
            },

Setting display content for a column

Column HTML content can be changed as per the condition using this function which will be triggered for each row with the signature as the row data.

        header: {
           'Link': {               
                title: "Link",
                visible: true,
                setDisplayContent: function (record) {
                    if (record.Standard == 8)
                        return "<a href='http://www.google.com'>google";
                }
            },
}

Saving records with grid in-built function

Updated records can be saved using the inbuilt function by providing the save action method in actions. Icon will be generated for save.

In Script:

            actions: {
                  bindingMethod: "/Vgrid/GetData",
                  saveMethod: "/Vgrid/Save"
              },

In Server Side:

public void Save(GridParams gridParams, List<student> updatedRecords, List<student> deletedRecords)
        {
            ///Code           
        }

Note: The argument for the save method should be updatedRecords.

Enabling the column resize functionality

Grid Column can be resized using the column resize settings

                  $('#sampleVgrid').VGrid({
                  columnResize: true//Default is false
                  }); 

Enabling the drag and drop functionality

Column's can be dragged and dropped in the grid using this functionality.Column can be dragged once the column to be dragged is right clicked and then it can be moved to the desired index in the grid.

   $('#sampleVgrid').VGrid({
                  dragDrop: true//Default is false
                  }); 

 

Note: Default value is false.

Enabling Custom Filter for the Grid

Custom filter can be enabled using the customFilter property.By default the column fields will be listed in the autocomplete textbox followed by type of search (Contains,Starts with and Equals) followed by the filter data text field.Number of filter can be added and removed using the add/remove buttons.

   $('#sampleVgrid').VGrid({
                  customFilter: true//Default is false
                  }); 

Customizing Delete functionality

Records can be deleted using the delete functionality.This will be enabled if we enable the save functionality.

   $('#sampleVgrid').VGrid({
                  eventHandlers: {
                   deleteCallBackHandler: function (rowData,rowHtmlObject) {
                         //if(!permission){
                         //return []; data will not be deleted
                         //}
                          return rowData;
                       }}
                  }); 

 

Sample Code Snippet for the Grid

$('#sampleVgrid').VGrid({
header: {
            Name: {
                title: "Student Name",//Column Title
                visible: true,//Column visibility (default value : true)
                width: '200px',//To set the width of thee column,
                textAlign: 'left'
            },
            Id: {
                title: "Student Id",
                width: '150px',
                textAlign: 'center'
            },
            Standard: {
                title: "Standard",
                editable: true,
                editType: 'dropDown',
                dropDownId:'standard',
                width: "250px",
            },
            Age: {
                title: "Student Age",
                visible: true,
                width: '250px',
            },
            'Grade': {
                parentClass: 'Academics',//To implement the associated class
                isComplex: true,//To implement the associated class
                title: "Grade",
                editable: true,
                editType: 'dropDown',
                dropDownId: 'grade',
                sortable: false,
                width: '250px',
            },
            'FathersName': {
                isComplex: true,
                parentClass: 'Details',
                editable: true,//To make the column editable
                title: "Father Name",
                width: '250px',
            },
            'MothersName': {
                isComplex: true,
                parentClass: 'Details',
                title: "Mother Name",
                width: '250px',

            },
            IsIndian: {                      
                editable: true,//To make the column editable
                title: "Is Indian",
                width: '250px',
                editType:'checkBox'
            },
            'FathersOccup': {
                isComplex: true,
                parentClass: 'Details',
                title: "Fathers Occupation",
                visible: true,
                width: '250px',
            },
            'MothersOccup': {
                isComplex: true,
                parentClass: 'Details',
                title: "Mother's Occupation",
                visible: true,
                width: '250px',
                setDisplayContent: function (record) {
                    if (record.Standard == 8)
                        return "<a href="http://www.google.com">google</a>";
                }                
            },
            Dob: {
                visible: true,                
                editable: true,
                editType: "dateTime",
                dateTimeFormat: "dd M yy",
                width:"250px"
            }
        },
        actions: {
            bindingMethod: "/Vgrid/GetData",
            saveMethod: "/Vgrid/Save",
            dropDownSourceMethod:'Vgrid/GetDropDownValues'
        },
        pageSize: 25,
        selection: 'multiple',
        eventHandlers: {
            onCallStart: function (args) {
                //Data to be posted on ajax request                
                args['name'] = $('#txtName').val();
                return args;
            },
            onCallSuccess: function (data) {
                //Handler for callback implementations                 
                return data;
            },
            selectionHandler: function (data) {                 
                //Handler for implementation after selection is made
                return data;
            },            
            saveActionCallBack: function (status) {
                alert("Saved Successfully");
            },
            cellSaveHandler: function (currentCellObj, oldValue, newValue) {                 
                //Do nothing
                //return modifiedValue
            },
            deleteCallBackHandler: function (rowData,rowObject) {
                //if(!permission){
                //return []; data will not be deleted
                //}
                return rowData;
            }
        },
        setTitle: true,//Sets the title to the cells value after the specified length(
        maxLenToDisp: 20,//Sets the title for the cells if the length of the character exceed this value
        multiplePageSelection: {//Enables the cross page selection
            uniqueIdentifier: 'Id',
        },
        tableStyle: {
            oddTrColor: '',
            oddTrTextColor: '',
            evenTrColor: '',
            evenTrTextColor: '',
            headerColor: '',
            headerTextColor: '',
            pagerBarColor: '',
            pagerBarTextColor: '',
            columnVisibilitypopColor: '',
            columnVisibilitypopTextColor: '',
            cellSpacing: "1"
        },
        columnVisibilitySetting: true,
        defaultLoad: true,
        columnResize: true,
        dragDrop:true,
        customFilter:true,
        gridMessages: {
            error: '',
            noRecordsFound: '',
            updatedChanges: '',
            columnHide: ''
        }
}); 

Conclusion

A few more functionalities will be added gradually.Kindly add a comment if you notice any bugs. Thanks in advance.

History

  • Version 1 : Grid with basic functionality added
  • Version 2 : Added column resize, save feature, improved styles and version 1 bug fixing
  • Version 2.1 : Added column drag drop feature, Added drop-down and date-time edit feature and CSS themes and version 2.0 bug fixes.
  • Version 2.2 : Added custom filter feature,Delete feature and Custom class for filter.Bug fixes on drag & drop and Alignment issues.
  • Version 2.3 : Added check box edit functionality and bug fixes on set content display,alignment issues.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

Share

About the Author

vijay venkatesh prasad N
Software Developer
India India
No Biography provided

Comments and Discussions

 
GeneralMy vote of 5 PinmemberAmbre Sachin27-Aug-14 1:48 
GeneralMy vote of 5 PinmemberSanjay K. Gupta26-May-14 19:33 
GeneralImpressive! PinmemberDaveX8626-May-14 9:50 
GeneralRe: Impressive! Pinmembervijay venkatesh prasad N26-May-14 22:54 
QuestionNice! PinprofessionalVolynsky Alex26-May-14 9:34 
QuestionGood Work PinmemberMember 1083163120-May-14 3:43 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web03 | 2.8.141216.1 | Last Updated 22 Aug 2014
Article Copyright 2014 by vijay venkatesh prasad N
Everything else Copyright © CodeProject, 1999-2014
Layout: fixed | fluid