65.9K
CodeProject 正在变化。 阅读更多。
Home

Jquery Grid (VGrid)

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.85/5 (18投票s)

2014年4月15日

CPOL

5分钟阅读

viewsIcon

42435

downloadIcon

2431

实现 Grid 的可重用工具

 

引言

 

VGRID 是一个轻量级、易于配置、跨浏览器兼容的网格,使用 JQUERY 构建。

在本文中,我们将介绍如何在 ASP.NET - MVC 中实现网格。

此网格具有以下内置功能

  • 冻结表头
  • 列可见性设置
  • 列内联编辑和行删除
  • 多页选择
  • 列宽、表格样式和 title 属性设置的自定义
  • 列调整大小
  • 列拖放和
  • 内置的蓝色和黑色主题
  • 自定义过滤器

使用网格

路线图

  • 配置具有基本功能的网格
  • 为特定列设置可见性
  • 禁用特定列的排序
  • 添加具有复杂关联的列
  • 启用特定列的编辑
  • 设置网格的选择模式
  • 为列设置标题
  • 启用 MultiPageSelection
  • 启用列可见性设置弹出窗口
  • 为表格设置颜色
  • 过滤数据的配置
  • 事件处理器
  • 检索选定的/更新的记录
  • 特定列的文本对齐设置
  • 设置列的显示内容
  • 使用网格内置功能保存记录
  • 启用列调整大小功能
  • 启用拖放功能
  • 为网格启用自定义过滤器
  • 自定义删除功能
  • 网格的示例代码片段

配置具有基本功能的网格

在需要实现网格的页面中,添加以下引用

    <!--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>    

Script 标签或引用的 JavaScript 页面中,添加以下代码

        $(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. 
    });
});

在服务器端,添加以下代码

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

为特定列设置可见性

可以使用 visibility 属性更改特定列的可见性。

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

注意:默认值为 true

禁用特定列的排序

可以使用 sortable 属性停止特定列的排序。

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

注意:默认值为 true

添加具有复杂关联的列

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

启用特定列的编辑

可以通过使用 editable 属性来编辑特定列。编辑类型可以通过 editType 属性设置。编辑类型包括日期时间编辑、下拉列表编辑和文本编辑。

启用文本编辑

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
        }
    }
}

启用下拉列表编辑

提供下拉列表数据源的 Action 方法

     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
            },
}

数据源的服务器代码

        /// <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;
            }
        }

日期时间编辑

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

复选框编辑

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

注意:默认值为 false

设置网格的选择模式

可以使用 selection 属性使网格可选择。默认情况下,网格不可选择。可以使用 selection 属性将其设置为多选或单选。

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

为列设置标题

可以使用此选项为列设置 Title 属性。maxLenToDisp 是设置该属性值大于等于的属性,然后为该列设置该属性。

$('#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     
});

启用多页选择

可以使用 multiplePageSelection 属性在页面之间进行选择。

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

启用列可见性设置弹出窗口

可以通过使用 columnVisibilitySetting 属性在网格中启用列可见性功能。

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

单击信息栏中的显示/隐藏按钮将打开列可见性弹出窗口。

注意:默认值为 false

为表格设置颜色

可以通过为所需属性提供值来定制网格的颜色。单元格间距设置用于设置单元格之间的间距。

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

过滤数据的配置

可以使用 onCallStart 函数过滤网格中的可用数据。

在脚本中添加以下代码

$('#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
});

在服务器端,添加以下代码

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

注意:args 中的变量和方法中的变量应相同。

事件处理器

Ajax 请求的回调处理程序

数据可以从此函数进行操作。此函数将在数据显示在网格中之前触发。

$('#sampleVgrid').VGrid({
     eventHandlers: {   
            callBack: function (data) {            
                  //Handler for callback implementations after post
                  ///Logic to manipulate the data                       
                  return data;
             }
        }
});
选择处理程序

做出选择后将立即触发此函数。它将可用于选择验证等。

$('#sampleVgrid').VGrid({
   eventHandlers: {    
            selectionHandler: function (data) {
                 //Handler for implementation after selection is made
                 return data;
            }
        }
});
单元格保存处理程序

此函数将在可编辑单元格保存后触发。

$('#sampleVgrid').VGrid({
 eventHandlers: { 
            cellSaveHandler: function (currentCellObj, oldValue, newValue) {                 
                //Do nothing
                return newValue
            }
        } 
});
保存回调处理程序

此函数是保存的回调处理程序。

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

检索选定的/更新的记录

Gridobject 以对象的形式检索更新/选定的行,该对象是与其绑定的行的数据。

//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;            
});

注意:此项的默认值是 undefined (如果没有更改或未选择任何行,则返回默认值)。

特定列的文本对齐设置

可以使用 textAlign 设置将文本对齐设置为居中/左对齐/右对齐。

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

设置列的显示内容

可以使用此函数根据条件更改列的 HTML 内容,该函数将为每一行触发,其签名与行数据相同。

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

使用网格内置功能保存记录

可以通过提供 actions 中的保存操作方法,使用内置函数来保存更新的记录。将生成保存图标。

在脚本中

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

在服务器端

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

注意save 方法的参数应为 updatedRecords

启用列调整大小功能

可以使用列调整大小设置来调整网格列的大小。

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

启用拖放功能

使用此功能可以在网格中拖放列。单击要拖动的列的右键,然后将其移动到网格中的所需索引,即可拖动列。

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

 

注意:默认值为 false。

为网格启用自定义过滤器

可以使用 customFilter 属性启用自定义过滤器。默认情况下,列字段将出现在自动完成文本框中,后跟搜索类型(包含、以...开头和等于)以及过滤器数据文本字段。可以通过添加/删除按钮添加和删除多个过滤器。

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

自定义删除功能

可以使用删除功能删除记录。如果启用保存功能,则此功能将被启用。

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

 

网格的示例代码片段

$('#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 "google";
                }                
            },
            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: ''
        }
}); 

结论

将逐渐添加更多功能。如果您发现任何错误,请发表评论。提前致谢。

历史

  • 版本 1:添加了基本功能的网格
  • 版本 2:添加了列调整大小、保存功能、改进了样式并修复了版本 1 的错误
  • 版本 2.1:添加了列拖放功能、下拉列表和日期时间编辑功能、CSS 主题,并修复了版本 2.0 的错误。
  • 版本 2.2:添加了自定义过滤器功能、删除功能和过滤器的自定义类。修复了拖放和对齐问题。
  • 版本 2.3:添加了复选框编辑功能,并修复了内容显示设置和对齐问题。
© . All rights reserved.