封装后的代码如下:

function DataGrid(options) {
this.options = {
height: "100%",
sortable: true,
reorderable: true,
scrollable: true,
filterable: {
mode: "menu",
extra: false,
operators: {
string: {
contains: "Contains",
equal: "Equal to"
}
}
},
editable: { mode: "popup" },
resizable: true,
columnMenu: true,
pageable: {
refresh: true,
pageSizes: true,
buttonCount: 5
},
dataSourceOptions: {
transport: {},
batch: true,
pageSize: 50,
schema: {
model: false,
data: function (d) {
return d.Data;
},
total: function (d) {
return d.RowCount;
}
},
serverPaging: true,
serverFiltering: true,
serverSorting: true
}
}; this.init = function () {
this.setOptions(options); var thatOptions = this.options.temp;
var self = this; // render KendoUI Grid
$("#" + thatOptions.id).kendoGrid(self.options); $("#" + thatOptions.id).addClass("grid-column-command-default");
return self;
}; this.setOptions = function (options) {
var self = this; //Only assign the property values the keys of which are included in 'options'
for (var property in options) {
if (this.options.hasOwnProperty(property) && property != "dataSourceOptions") {
this.options[property] = options[property];
}
}
this.options.temp = options; // cache the old options // Append each item to toolbar container
if (options.toolbar) {
this.setToolbar(options);
} this.setDataSource(options); this.setColumns(options); if (options.showCheckBox) {
this.options.columns.unshift({
headerTemplate: '<input type="checkbox" />',
template: '<input type="checkbox" />',
width: 35
});
} this.options.dataBound = function () {
options.gridActions && options.gridActions.edit && self.bindRowDblClick();
options.contextMenuOptions && self.bindRowContextMenu();
options.showCheckBox && (typeof self.bindHeaderCheckBoxClick == "function") && self.bindHeaderCheckBoxClick();
var id = options.id;
$("#" + id + " tbody tr[role=row]").each(function () {
if (!$("#" + id).data("kendoGrid")) {
return;
}
var rowItem = $("#" + id).data("kendoGrid").dataItem($(this));
var status = rowItem.Status;
if (status && status != "Active") {
$(this).addClass("row-inactive").addClass("row-inactive-" + status);
}
var isHighlighted = rowItem.IsHighlighted;
if (isHighlighted) {
$(this).addClass("row-highlighted");
}
}); self.bindClearAllFiltersClick();//clear all filters (default function) (typeof options.dataBound == "function") && options.dataBound(); $("#" + id + " .k-grid-create").off("click").on("click", function (e) {
e.preventDefault();
self.showDialog(null, self, options);
}); self.resize();
}; this.options.edit = function (e) {
if (options.editable && typeof window[options.editable.rowEditCallback] == "function") {
window[options.editable.rowEditCallback](e);
}
};
this.options.remove = function (e) {
if (options.editable && typeof window[options.editable.rowRemoveCallback] == "function") {
window[options.editable.rowRemoveCallback](e);
}
};
this.options.save = function (e) {
if (typeof options.save == "function") {
options.save(e); //Force to reload the data of gridview
var timer = setInterval(function () {
if ($("#" + options.id).data("ajaxcompleted")) {
clearInterval(timer);
self.refresh();
}
}, 500);
}
};
this.options.filter = function (e) {
if (e.filter && e.filter.filters) {
for (var i = 0; i < e.filter.filters.length; i++) {
var item = e.filter.filters[i];
item.value = item.value.replace(/^\s*└\s*/g, "");
}
}
$('#' + options.id + ' .alert-warning').remove();
};
}; this.setDataSource = function (options) {
var self = this;
if (options.dataSourceOptions) {
var thatOptions = options;
this.options.dataSourceOptions.transport = {
read: {
type: "post",
url: options.dataSourceOptions.read,
dataType: "json",
contentType: "application/json"
},
update: {
type: "post",
url: options.dataSourceOptions.update,
dataType: "json",
contentType: "application/json"
},
create: {
type: "post",
url: options.dataSourceOptions.update,
dataType: "json",
contentType: "application/json"
},
destroy: {
type: "post",
url: options.dataSourceOptions.destroy,
dataType: "json",
contentType: "application/json"
},
parameterMap: function (options, operation) {
if (operation === "read") {
var criteria = {
Limit: options.take || 50,
Offset: options.skip || 0
};
if (options.filter && options.filter.filters) {
criteria.PostFilters = options.filter.filters;
//Assign the column datatype
for (var i = 0; i < criteria.PostFilters.length; i++) {
for (var j = 0; j < thatOptions.columns.length; j++) {
if (criteria.PostFilters[i].field == thatOptions.columns[j].field) {
criteria.PostFilters[i].DataType = thatOptions.columns[j].filterDataType;
continue;
}
}
}
} if (options.sort && options.sort.length > 0) {
criteria.SortBy = options.sort[0].field;
criteria.SortDirection = options.sort[0].dir + "ending";
} // Apply custom parameterMap logic
var grid = $("#" + thatOptions.id).data("kendoGrid");
var customParamMap = grid.options.temp.dataSourceOptions.customParamMap;
if (customParamMap) {
criteria = customParamMap(criteria);
}
grid.options.temp.criteria = criteria;//Cache the all filters
return kendo.stringify(criteria);
} if (operation === "create" || operation === "update") {
if (thatOptions.editable && thatOptions.editable.mode == "inline") {
return kendo.stringify(options.models ? options.models[0] : {});
}
}
if (operation === "destroy") {
if (thatOptions.editable && thatOptions.editable.mode == "inline") {
return kendo.stringify(options.models ? options.models[0] : {});
}
}
}
}; this.options.dataSourceOptions.schema.model = {
id: "Id",
fields: options.dataSourceOptions.modelFields
};
this.options.dataSourceOptions.pageSize = options.dataSourceOptions.pageSize || 50; this.options.dataSourceOptions.requestStart = function (e) {
$("#" + options.id).data("ajaxcompleted", false);
};
this.options.dataSourceOptions.requestEnd = function (e) {
$("#" + options.id).data("ajaxcompleted", true);
};
}
this.options.dataSource = new kendo.data.DataSource(this.options.dataSourceOptions);
}; this.setColumns = function (options) {
var columnsOptions = options.columnsOptions || {};
//Fetch columns data from server
$.ajax({
type: "post",
url: columnsOptions.url || "/GridView/GetColumnHeaders",
data: columnsOptions.params || { metaType: options.metaType },
dataType: "json",
async: false,
success: function (data) {
options.columns = data;
}
}); //Set filter-menu features of each column
this.setFilterMenus(options); //Enable Row-Editing function
if (options.editable && options.editable.mode == "inline") {
options.editable.commandColumn && options.columns.push(options.editable.commandColumn);
} this.options.columns = options.columns;
}; this.setFilterMenus = function (gridOptions) {
gridOptions.columns && $(gridOptions.columns).each(function (index, column) {
var serviceOptions = {
transport: {
read: {
type: "post",
url: column.filterControlDataService,
dataType: "json",
contentType: "application/json"
},
parameterMap: function (options, operation) {
if (operation === "read") {
var criteria = {};
if (options.filter && options.filter.filters && options.filter.filters.length) {
criteria = options.filter.filters[0];
}
return kendo.stringify(criteria);
}
}
},
serverFiltering: true
}; var filterableOptions = null;
switch (column.filterControlType) {
case 1://DropDownList
if (column.filterDataType == 2) {
serviceOptions = [{ Text: "false", Value: "false" }, { Text: "true", Value: "true" }];
}
filterableOptions = {
operators: {
string: {
equal: "Equal to"
}
},
ui: function (element) {
element.kendoDropDownList({
autoWidth: true,
filter: "contains",
dataTextField: "Text",
dataValueField: "Value",
dataSource: serviceOptions
});
}
};
break;
case 3://AutoComplete
filterableOptions = {
operators: {
string: {
contains: "Contains"
}
},
ui: function (element) {
element.kendoAutoComplete({
autoWidth: true,
filter: "contains",
dataTextField: "Text",
dataValueField: "Value",
dataSource: serviceOptions
});
}
};
break;
default:
break;
} $.extend(column, {
filterable: filterableOptions
});
});
}; this.setToolbar = function (options) {
if (!options.toolbar) {
return;
}
if (options.toolbar === "All") {
options.toolbar = {
items: [{ name: "addRecord", text: "Add Record" },
{ name: "importExcel", text: "Excel Bulk Edit" },
{ name: "excel", text: "Generate Excel Report" },
{ name: "pdf", text: "Generate PDF Report" },
{ name: "clearFilters", text: "Clear All Filters" }]
};
} var toolbarItems = [];
options.toolbar.items && $(options.toolbar.items).each(function (index, toolItem) {
var displayOrNot = toolItem.display == "always" ? "" : " style='display:none;'";
switch (toolItem.name) {
case "addRecord":
toolbarItems.push({ template: "<a role='button' class='k-button k-button-icontext k-grid-create' href='javascript:void(0);'" + displayOrNot + "><span class='k-icon k-i-plus'></span>" + toolItem.text + "</a>" });
break;
case "importExcel":
var dropdownListId = options.id + "_bulk_edit";
var dropdownTemplate = "<div class='dropdown' style='display: inline-block;'><a id='" + dropdownListId + "' role='button' class='k-button k-button-icontext k-grid-import' href='javascript:void(0);' " + displayOrNot + " data-toggle='dropdown' aria-haspopup='true' aria-expanded='true'><span class='k-icon k-i-menu'></span> " + toolItem.text + "</a>";
dropdownTemplate += "<ul id='" + dropdownListId + "DropDownMenu' class='dropdown-menu' aria-labelledby='" + dropdownListId + "'>";
dropdownTemplate += "<li><a href='javascript:void(0)' id='btn_" + dropdownListId + "_by_search'><i class='fa fa-fw fa-file-excel-o mr-5'></i><span class='ml-5'>Download template for Current Search</span></a></li>";
dropdownTemplate += "<li><a href= 'javascript:void(0)' id= 'btn_" + dropdownListId + "_by_all' ><i class='fa fa-fw fa-file-excel-o mr-5'></i><span class='ml-5'>Download template for All Records</span></a></li>";
dropdownTemplate += "<li role='separator' class='divider'></li>";
dropdownTemplate += "<li><a href='javascript:void(0)' id='btn_" + dropdownListId + "_by_custom'><i class='fa fa-fw fa-upload mr-5'></i><span class='ml-5'>Import Bulk Edit Worksheet</span></a></li>";
dropdownTemplate += "</ul></div>";
toolbarItems.push({ template: dropdownTemplate });
break;
case "excel":
toolbarItems.push({ name: "excel", text: toolItem.text });
options.excel = {
fileName: "ExcelReport.xlsx",
proxyURL: "/GridView/GenerateExcelReport",
filterable: true
};
break;
case "pdf":
toolbarItems.push({ name: "pdf", text: toolItem.text });
options.pdf = {
allPages: true,
avoidLinks: true,
paperSize: "A4",
margin: { top: "2cm", left: "1cm", right: "1cm", bottom: "1cm" },
landscape: true,
repeatHeaders: true,
template: '<div class="page-template">' +
'< div class="header" >' + '<div style="float: right">Page #: pageNum # of #: totalPages #</div>' +
'</div>' +
'<div class="watermark">M+W Group</div>' +
'<div class="footer">Page #: pageNum # of #: totalPages #</div>' +
'</div>',
scale: 0.8
};
break;
case "create":
toolbarItems.push({ name: "create", text: "Add", template: "<a role=\"button\" class=\"k-button k-button-icontext k-grid-add\" href=\"##\"" + displayOrNot + "><span class=\"k-icon k-i-plus\"></span>" + toolItem.text + "</a>" });
break;
case "clearFilters":
toolbarItems.push({ template: "<a role='button' class='k-button k-button-icontext k-grid-clearfilters pull-right' href='javascript:void(0);'><span class='k-icon k-i-filter-clear'></span>" + toolItem.text + "</a>" });
break;
default:
toolbarItems.push(toolItem);
break;
}
});
this.options.toolbar = toolbarItems;
};
this.clearAllFilters = function () {
var options = this.options.temp;
$("#" + options.id).find(".k-grid-toolbar .k-grid-clearfilters").click();
};
this.bindClearAllFiltersClick = function () {
var options = this.options.temp;
//Clear the selected filters of gridview
$("#" + options.id).find(".k-grid-toolbar .k-grid-clearfilters").off("click").on("click", function (e) {
e.preventDefault();
//Clear gridview filters:
var grid = $("#" + options.id).data("kendoGrid");
grid.options.temp.dataSourceOptions.customParamMap = function (criterias) {
criterias.MetaType = grid.options.temp.MetaType;
return criterias;
};
var datasource = grid.dataSource;
datasource.filter([]); $("#" + options.id + " .alert-warning").remove();
});
} this.bindRowDblClick = function () {
var thatOptions = this.options.temp;
var self = this;
$("#" + thatOptions.id + " tbody tr[role=row]").off("dblclick").on("dblclick", function (e) {
e.preventDefault();
self.showDialog($(this), self, thatOptions);
});
}; this.bindRowContextMenu = function () {
var that = this;
var thatOptions = that.options.temp; if (!thatOptions.contextMenuOptions) {
return;
} var defaultRemoveAction = function (e) {
var dataKey = $("#" + thatOptions.id).data("kendoGrid").dataItem(e.target).Id;
kendo.confirm("The data of this row will be deleted, are you sure to proceed?").then(function () {
$.post(thatOptions.gridActions.remove + "/" + dataKey, function (d) {
if (d && d.Ok) {
that.refresh();
}
});
});
}
var menuItems = [
{ name: "view", onClick: function (e) { that.showDialog(e.target, that, thatOptions); } },
{ name: "edit", onClick: function (e) { that.showDialog(e.target, that, thatOptions); } },
{ name: "remove", onClick: defaultRemoveAction }
];
thatOptions.contextMenuOptions.items && $(thatOptions.contextMenuOptions.items).each(function (index, item) {
for (var i = 0; i < menuItems.length; i++) {
if (menuItems[i].name == item.name) {
if (!item.onClick) {
item.onClick = menuItems[i].onClick;
}
}
}
}); var contextMenuOptions = {
targetId: thatOptions.id,
filter: "tbody tr[role=row]",
items: thatOptions.contextMenuOptions.items || menuItems,
metaType: thatOptions.metaType
};
new ContextMenu(contextMenuOptions).init();
}; this.showDialog = function (target, grid, options) {
var dataKey = "", url;
if (target) {
dataKey = $("#" + options.id).data("kendoGrid").dataItem($(target)).Id;
url = $.format("{0}/{1}", options.gridActions.edit, dataKey);
} else {
url = options.gridActions.create;
}
new ModalDialog({
id: options.id + "_dialog",
title: options.metaType,
content: url,
dataKey: dataKey,
metaType: options.metaType,
showSave: true,
callbackAfterSaving: function () {
grid.refresh();
}
}).show();
}; // Select multiple rows through checking the checkbox in front of each data rows
this.bindHeaderCheckBoxClick = function () {
var thatOptions = this.options.temp;
$("#" + thatOptions.id + " thead tr[role=row] th:first-child :checkbox").on("click", function () {
var parentCheckBox = $(this);
$("#" + thatOptions.id + " tbody tr[role=row] td:first-child :checkbox").each(function () {
$(this).prop("checked", $(parentCheckBox).prop("checked"));
});
}); $("#" + thatOptions.id + " tbody tr[role=row] td:first-child :checkbox").on("click", function () {
var parentCheckBox = $("#" + thatOptions.id + " thead tr[role=row] th:first-child :checkbox");
if ($("#" + thatOptions.id + " tbody tr[role=row] td:first-child :checked").size() != $("#" + thatOptions.id + " tbody tr[role=row] td:first-child :checkbox").size()) {
parentCheckBox.prop("checked", false);
} else {
parentCheckBox.prop("checked", true);
}
});
}; this.refresh = function () {
var self = this;
var thatOptions = this.options.temp;
if ($("#" + thatOptions.id).data("kendoGrid")) {
$("#" + thatOptions.id).data("kendoGrid").dataSource.read();
}
var timer = setTimeout(function () {
clearTimeout(timer);
self.options.dataBound && self.options.dataBound();
self.resize();
}, 50);
}; this.resize = function () {//Fix Grid Height autofit issue
var thatOptions = this.options.temp; var timer = setTimeout(function () {
clearTimeout(timer);
var gridElement = $("#" + thatOptions.id),
dataArea = gridElement.find(".k-grid-content"),
gridHeight = gridElement.innerHeight(),
otherElements = gridElement.children().not(".k-grid-content"),
otherElementsHeight = 0;
otherElements.each(function () {
otherElementsHeight += $(this).outerHeight();
});
dataArea.height(gridHeight - otherElementsHeight);
}, 500);
};
return this;
} // Provider a Grid Widget Plugin
$(function () {
$.fn.extend({
dataGrid: function (options) {
return this.each(function () {
var selfOptions = $(this).data();
if (selfOptions.optionsKey && window[selfOptions.optionsKey]) {
$.extend(selfOptions, window[selfOptions.optionsKey]);
}
selfOptions.id = $(this).prop("id"); var dataSourceOptions = selfOptions.dataSourceOptions || {};
selfOptions.dataSourceOptions = {
read: ((dataSourceOptions ? dataSourceOptions.read : null) || "/GridView/GetDataSource"),
update: (dataSourceOptions ? dataSourceOptions.update : null),
destroy: (dataSourceOptions ? dataSourceOptions.destroy : null),
modelFields: selfOptions.modelFields,
customParamMap: function (criteria) {
criteria.PreFilters = options.preFilters || selfOptions.preFilters;
criteria.PostFilters = options.postFilters || []; selfOptions.postFilters && $(selfOptions.postFilters).each(function (index, item) {
criteria.PostFilters.push(item);
}); criteria.MetaType = options.metaType || selfOptions.metaType;
return criteria;
},
pageSize: dataSourceOptions.pageSize || 50
}; if (selfOptions.filterable == undefined) {
selfOptions.filterable = false;
}
if (selfOptions.columnMenu == undefined) {
selfOptions.columnMenu = false;
}
if (selfOptions.pageable == undefined) {
selfOptions.pageable = false;
} if (options) {
$.extend(selfOptions, options);
} var instance = new DataGrid(selfOptions).init();
$(this).data("cutomeGrid", instance);
});
}
});
});
 

使用场景:

 <div id="gridDeliverables"
data-role="custom_grid"
data-toolbar='[{ "name": "addRecord", "text": "Add Record" },
{ "name": "importExcel", "text": "Import from Excel" },
{ "name": "excel", "text": "Export to Excel" },
{ "name": "pdf", "text": "Export to PDF" }]'
data-dialog-Options='{"id": "PackageDeliverableDialog","title": "Deliverable"}'
data-sortable="true"
data-reorderable="true"
data-filterable="false"
data-column-Menu="false"
data-height=""
data-url="@Url.Action("GetDataSource", "GridView")"
data-filters='[{ "Field": "PrimaryPackageId", "Value": "@Model.Id", "Operator": "Eq" }]'
data-meta-Type="@MetaType.Deliverables"
data-grid-Columns-Url="@Url.Action("GetColumnHeaders", "GridView")"
data-grid-Columns-Params='{ "metaType": "@MetaType.Deliverables" }'
data-grid-Row-Create-Url='@Url.Action("Create", "DesignDeliverable")'>
</div>

全局触发处理:

  $(".dialog [data-role=custom_grid]").each(function () {// Render cunstom grid by hand
var self = $(this);
setTimeout(function () {
if (!self.data("kendoGrid") && !self.data("rendercompleted")) {
var options = self.data();
options.id = self.prop("id");
options.dataSourceOptions = {
url: options.url,
customParamMap: function (criterias) {
criterias.Filters = options.filters || [];
criterias.MetaType = options.metaType;
return criterias;
}
};
$.kendoGrid.init(options);
self.data("rendercompleted", true);
}
}, 1000);
});

封装扩展Kendo UI Grid的更多相关文章

  1. kendo ui grid选中行事件,获取combobox选择的值

    背景: 以前用 telerik ui做的grid现在又要换成kendo ui,不过说句实话kendo ui真的比telerik好多,可以说超级升级改头换面.当然用的mvc的辅助方法,以前的teleri ...

  2. Kendo UI Grid 使用总结

    Kendo UI Grid控件的功能强大,这里将常用的一些功能总结一下. Kendo UI Grid 固定列 在使用Gird控件显示数据时,如果数据列过多,会出现横向滚动条,很多情况下,我们希望某些列 ...

  3. Kendo UI Grid 批量编辑使用总结

    项目中使用Kendo UI Grid控件实现批量编辑,现在将用到的功能总结一下. 批量编辑基本设置 Kendo Grid的设置方法如下: $("#grid").kendoGrid( ...

  4. Asp.net mvc Kendo UI Grid的使用(二)

    上一篇文章对Kendo UI做了一些简单的介绍以及基本环境,这篇文章来介绍一下Grid的使用 先上效果图: 要实现这个效果在Controller在要先导入Kendo.Mvc.UI,Kendo.Mvc. ...

  5. [Asp.net mvc] Asp.net mvc Kendo UI Grid的使用(四)

    有段时间没写博客了,工作状态比较忙,抽空继续总结下Grid的使用,这次主要介绍模板以及其他官网介绍不详尽的使用方法.先Show出数据,然后讲解下.后台代码: public ActionResult O ...

  6. kendo ui grid 汉化

    加入js引用 <link href="http://cdn.kendostatic.com/2014.2.716/styles/kendo.common.min.css" r ...

  7. Asp.net mvc Kendo UI Grid的使用(三)

    上一篇的操作已经能够显示基本数据了,这次介绍一下如何进行数据操作以及显现自定义命令. 第一步当然还是准备数据: [HttpPost] public ActionResult PersonalList_ ...

  8. kendo ui - grid 数据表格系列

    kendo-ui 官网:https://www.telerik.com/documentation 初始化 grid: 引入文件: <link rel="stylesheet" ...

  9. kendo ui grid控件在选择行时如何取得所选行的某一列数据

    $("#grid").kendoGrid({ dataSource: dataSrc, columns: [ { template: '#=material_id#', width ...

随机推荐

  1. [考试反思]1007csp-s模拟测试63:朦胧

    别找了原来没有写过叫<朦胧>的我check过了.(慌的一匹) 总算是比较早的改完了一套题. 但是考的是个啥啊... 前两道题都很卡常导致我想到了正解但是都放弃了. 2e8的复杂度怎么可能能 ...

  2. Apache配置反向代理、负载均衡和集群(mod_proxy方式)

    Apache配置负载均衡和集群使用mod_jk的方式比较多,但是mod_jk已经停止更新,并且配置相对复杂.Apache2.2以后,提供了一种原生的方式配置负载均衡和集群,比mod_jk简单很多. 1 ...

  3. python编程【环境篇】- 如何优雅的管理python的版本

    简介 之前的文章(Python2还是python3 )中我们提到,建议现在大家都采用python3,因为python2在今年年底将不在维护.但在实际的开发和使用python过程中,我们避免不了还得用到 ...

  4. 用js给元素增加链接

    <!DOCTYPE html><html>    <head>        <meta charset="UTF-8">      ...

  5. P2115 [USACO14MAR]破坏(二分答案)

    给定一串数,问删除中间一段,剩下的平均数最小是多少: 不容易想到这是个二分. $solution:$ 来手玩一点式子: 首先很容易想到一个前缀和$sum_i $表示i到1的前缀和,这样就能很容易地O( ...

  6. 「Usaco2012 Dec」第一(字典树+拓扑排序)

    (我恨字符串) 惯例化简题目:给定n个字符串,可以改变字符的相对大小(在字典序中的大小),问:字符串i是否能成为最小的字符串(字典序) 解题过程: 首先你可以预处理出来26的全排列然后暴力然后你只要用 ...

  7. 演示vsftpd服务匿名访问模式、本地用户模式的配置

    文件传输协议(FTP,File Transfer Protocol) 即能够让用户在互联网中上传.下载文件的文件协议,而FTP服务器就是支持FTP传输协议的主机,要想完成文件传输则需要FTP服务端和F ...

  8. 给一个整数数组,找到两个数使得他们的和等于一个给定的数 target。

    描述 给一个整数数组,找到两个数使得他们的和等于一个给定的数 target. 你需要实现的函数twoSum需要返回这两个数的下标, 并且第一个下标小于第二个下标.注意这里下标的范围是 0 到 n-1. ...

  9. php修改网站默认编码

    php修改网站默认编码网站如果header 不指定utf8默认 不是utf8 所以输入中文显示会乱码 一般都是apache不是不是utf8 打开 apache 配置文件 httpd.conf 加个 A ...

  10. vue之注册自定义的全局js方法

    前端开发的时候,总会需要写一些js方法,在vue框架中为了方便使用,可以考虑注册一个全局的js方法,下面是注册步骤: 1.0 可以在assets文件中的js文件下面新建一个js文件,如:yun.js- ...