kendo grid应用经验总结

学习网址

https://docs.telerik.com/kendo-ui/controls/editors/dropdownlist/overview

https://demos.telerik.com/aspnet-mvc/dropdownlist

https://www.cnblogs.com/libingql/p/3770758.html

目录

1、自定义toolbar

2、update data及事件捕捉

3日期显示及标题样式

4读取数据(传参)

5grid插入数据

6、template展开里面小项

7、clientTemplate 超链接形式

8、sync,事件

9、requestEnd事件

10、行内编辑事件,监听具体cell的修改

11、判断行内数据是否被修改

12、改变特殊行的字体颜色

13、超链接

14行头加复选框

15、kendo grid行内写编辑按钮

16初始排序

17、bool型foreignkey

18 clientTemplate

19基本应用及序号,action load data

20、js修改grid的datasource,column等

21、获取筛选排序参数post出去用于导出数据等

22、待grid绑定完数据设置高度,避免出现垂直滚动条

1、自定义toolbar

.ToolBar(toolbar =>
{
toolbar.Template(@<text>
<div class="toolbar">
<button id="import" class="btn btn-primary btn-sm">调取公司</button>
@* <button id="delete" class="btn btn-primary btn-sm">删除</button>*@
</div>
</text>);
})

2、update data及事件捕捉

.Update(read => read.Action("SaveAddPlans", "PlanManagement"))
.Events(events => events.Error("getError"))
.Events(events => events.RequestEnd("updateSuccess"))

3日期显示及标题样式

columns.Bound(p => p.PlanCheckDate).Format("{0:yyyy-MM-dd}").Title("<span style='color:red;'>*</span>计划检查时间").Width(120).EditorTemplateName("PlanCheckDate");
4读取数据(传参)

.Read(read => read.Action("LoadCompanies", "PlanManagement").Data("getCompanyFilter"))

function getCompanyFilter() {
return {
idFilter: $("#IdFilter").val(),
watchCategoryIdFilter: $("#WatchCategoryIdFilter").val(),
doorCategoryValueFilter: $("#DoorCategoryValueFilter").val()
};

5grid插入数据

originDataSource.insert({ CompanyId: tempRow[tempIndex].CompanyId, Name: tempRow[tempIndex].Name, DepartmentId: null, OperatorId: null, PlanCheckDate: null, Comment: null, Id: null, PlanCheckContentId: null, PlanCheckContent: { Value: null, Text: "请选择" }, Department: { Value: null, Text: "请选择" }, Operator: { Value: null, Text: "请选择" } });

6、template展开里面小项

.ToClientTemplate())

<script id="template" type="text/kendo-tmpl">
@(Html.Kendo().Grid<CompanyWatchPlanModel>()
.Name("InnerGrid#=Id#")
.HtmlAttributes(new { style = "width:900px;" })
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.PlanCheckDate).Editable(false);
model.Field(p => p.PlanExecuteStatusId).Editable(false);
})
.Read(read => read.Action("GetPlanAccordingToCompanyId", "PlanManagement", new { id = "#=Id#" }))
)
.EnableCustomBinding(true)
.Columns(columns =>
{
columns.Bound(o => o.Id).Title("执法任务编号").Width(100);
columns.Bound(p => p.PlanCheckDate).Format("{0:yyyy-MM-dd}").Title("计划检查时间").Width(120);
columns.ForeignKey(o => o.PlanExecuteStatusId, (IEnumerable)ViewData["PlanExecuteStatuses"], "Value", "Text").Title("计划执法状态").Width(100);
})
.ToClientTemplate())
</script>

7、clientTemplate 超链接形式

columns.Bound(p => p.PhotoLocation).ClientTemplate("# if (PhotoLocation=='') {#" + "无" + "#}#" + "# if (PhotoLocation!='') {#" + Html.ActionLink("影像浏览", "ReviewFile", "CommonAjax",
new { folderName = "SafeWatchApi/RejectCheckItemPhotos/upload", fileBasename = "#= getBaseName(PhotoLocation)#", extendName = "#= getExtendName(PhotoLocation)#" }
, new { target = "_blank" }).ToHtmlString() + "#}#").Title("影像浏览").Width(90).Filterable(false).Sortable(false);

function getBaseName(fileName) {
return fileName.substring(fileName.lastIndexOf('/')+1, fileName.lastIndexOf('.'));
}

function getExtendName(fileName) {
return fileName.substring(fileName.lastIndexOf('.'),fileName.length);
}

8、同步更新数据

.Update(read => read.Action("SaveTempMissions", "PlanSchedule").Type(HttpVerbs.Post).Data("getAllFiles"))

$("#confirmOk").click(function () {

$("#PlansGrid").data("kendoGrid").dataSource.sync();
});

9、requestEnd事件,可以用e.type来判断执行的某种操作请求。完成后可进一步处理

.Read("ReadTownEmploymentTargetList", "EHAdmin")
.Update("EditTownEmploymentTargetList", "EHAdmin")
.Create("CreateTownEmploymentTargetList", "EHAdmin")
.Events(events => events.RequestEnd("refreshGrid"))

function refreshGrid(e) {
if (e.type != "read") {
var grid = $("#TownEmploymentTargetGrid").data("kendoGrid");
grid.dataSource.read();

}
}

10、行内编辑事件,监听具体cell的修改

.Events(x => x.Edit("GridEdit"))
//.Selectable(selection => selection.Enabled(true))
.Groupable(grouping => grouping.Enabled(true))

function GridEdit(e) {
$("[name='UserName']").change(function () {
var userName = $(this).val();
var url = '@Url.Action("IsEmploymentHelpUserNameExist", "EHAdmin")';
$.post(url, { userName: userName }, function (isExist) {
if (isExist) {
alert("该用户名已存在,请重新选择填写!");
$("[name='UserName']").val("").focus();
}
});
});

//判断是否行内新增

if (!e.model.isNew()) {
$("[name='IdentityCode']").data("kendoDropDownList").enable(false);
};
}

11、判断行内数据是否被修改

var data = $("#OldGrid").data("kendoGrid").dataSource.data();
for (var k = 0; k < data.length; k++) {
if (data[k].dirty) {
changed = true;
break;
}
}

12、改变特殊行的字体颜色

.Filterable()
.Scrollable(x => x.Enabled(true))
.Scrollable(scr => scr.Height(280))
.Resizable(resize => resize.Columns(true))
.Events(e => e.Change("onChange"))
.Events(e => e.DataBinding("onDataBinding"))
.Events(events => events.DataBound("getSuccess"))

function getSuccess() {
var nowDate = new Date();
var grid = $("#MissionsGrid").data("kendoGrid");
var data = grid.dataSource.data();
$.each(data, function (i, row) {
if (row.ScheduleExecuteDate >= nowDate)
$('tr[data-uid="' + row.uid + '"] ').css("color", "#ff0000");
});
}

13、超链接

(1)columns.Bound(p => p.FileTypeText).ClientTemplate(Html.ActionLink("#= FileTypeText #", "ReviewFile", "CommonAjax",
new { folderName = "SafeWatchApi/Pdfs/uploadPdf/123", fileBasename = "#= getBaseName(FileLocation)#", extendName = ".pdf" }, new { target = "_blank" }).ToHtmlString())).Title("详情").Width(30).Filterable(false).Sortable(false);

function getBaseName(fileName) {
return fileName.substring(0, fileName.lastIndexOf('.'));
}

(2)columns.Bound(p => p.DepartmentTypeKey).ClientTemplate("<a href=#=buildUrl(DepartmentTypeKey)# target= '_self'>>></a>").Title("详情").Width(30).Filterable(false).Sortable(false);

function buildUrl(departmentTypeKey) {
var url= "@Url.Action("RealCompleteTotalStats", "Stats",
new
{
yearFilter = "__yearFilter__",
minMonthFilter = "__minMonthFilter__",
maxMonthFilter = "__maxMonthFilter__",
departmentTypeFilter = "__departmentTypeFilter__"
})";
return url.replace("__yearFilter__", yearFilter).replace("__minMonthFilter__", minMonthFilter).replace("__maxMonthFilter__", maxMonthFilter)
.replace("__departmentTypeFilter__", departmentTypeKey).replace(/amp;/g, "");
}

14行头加复选框

<link href="@Url.Content("~/Content/blue.css")" rel="stylesheet">
<script src="@Url.Content("~/Scripts/icheck.js")"></script>

columns.Bound(p => p.IsSelected).ClientTemplate("<input type='checkbox' class='icheckbox_square-blue iradio_square-blue' onclick='SetCheckBox(this)' />").Width(32).Title("");

function SetCheckBox(element) {
var row = $(element).parent().parent();
var data = $("#PlansGrid").data("kendoGrid").dataItem(row);
//checkstatuesid 1 means uncheck,2 means checked
if (data.CheckStatusId > 1) {
alert("正在调度中");
element.checked = false;
}
else {
if (data.CheckStatusId == "1") {
if (element.checked) {
uncheckedPlanIds.push(data.Id);
}
else {
for (var i = 0; i < uncheckedPlanIds.length; i++) {
if (uncheckedPlanIds[i] == data.Id) {
uncheckedPlanIds.slice(i, 1);
break;
}
}
}
}

15、kendo grid行内写编辑按钮 

columns.ForeignKey(p => p.IsFreeEquipment, (IEnumerable)ViewData["isOrNotList"], "Value", "Text").Title("是否<br>免费设备").Width(70);
columns.Command(command => { command.Custom("编辑").Click("edit"); command.Custom("删除").Click("deleteRecord"); }).Width(120);

function edit(e) {
e.preventDefault();
var dataItem = this.dataItem($(e.currentTarget).closest("tr"));
$("#Id").val(dataItem.Id);
$("#window").data("kendoWindow").setOptions({
title: "编辑洗碗机主数据"
});
$("#window").data("kendoWindow").center().open();
}

16初始排序

.Read(read => read.Action("LoadTestSummaryHistories", "CompanySummary").Data("getFilter"))
.Sort(sort => sort.Add(m => m.TestDate).Ascending())

.Sort(sort => sort.Add(m => m.GovernmentSafeRankResult).Ascending())

17、bool型foreignkey

columns.ForeignKey(p => p.CheckResult, (IEnumerable)ViewData["IsValidList"], "Value", "Text").ClientTemplate("#= (CheckResult == true) ? '合格 ' : '不合格' #").Title("检查结论").Width(120);

public List<SelectItemDto> GetIsValidList()
{
return new List<SelectItemDto>() { 
new SelectItemDto{ Text ="合格",Value = "True"},
new SelectItemDto{ Text ="不合格",Value = "False"}
};
}

18 clientTemplate

columns.Bound(m => m.Id).ClientTemplate("#= getRowNumber()# #=(IsNumberCancellation == true) ? '销户' : '' #").Title("序号").Width(60).Sortable(false).Filterable(false);

19基本应用及序号,action load data

<div class="row">
<div class="col-sm-12">
@(Html.Kendo().Grid<MachineMasterViewModel>()
.Name("DemandGrid")
.DataSource(dataSource => dataSource
.Ajax()
.Model(model =>
{
model.Id(p => p.Id);
model.Field(p => p.Name);
model.Field(p => p.BrandId);
})
.Read(read => read.Action("LoadMachines", "MachineMaster").Data("getFilter"))
.Events(events => events.Error("getError"))
.PageSize(10)
)

.ToolBar(toolbar =>
{
toolbar.Template(@<text>
<div class="toolbar">
<button id="import" class="btn btn-primary btn-sm">调取公司</button>
@* <button id="delete" class="btn btn-primary btn-sm">删除</button>*@
</div>
</text>);
})
.EnableCustomBinding(true)
.Columns(columns =>
{
columns.Bound(p => p.Id).ClientTemplate("#= getRowNumber() #").Title("序号").Width(40).Sortable(false);
columns.ForeignKey(p => p.BrandId, (IEnumerable)ViewData["brands"], "Value", "Text").Title("品牌").Width(70);
columns.Bound(o => o.Name).Title("洗碗机型号").Width(70);
columns.Command(command => { command.Custom("编辑").Click("edit"); command.Custom("删除").Click("deleteRecord"); command.Custom("查看").Click("showDetails"); }).Width(120);
})
.AutoBind(true)
.Events(e => e.DataBinding("onDataBinding"))
.Pageable(pageable => pageable
.Refresh(true)
.PageSizes(new[] { 10, 15, 20, 25, 50, 100 })
.ButtonCount(5))
.Scrollable(x => x.Enabled(true))
.Scrollable(scr => scr.Height(400))
)
</div>
</div>

<script>
var rowNumber = 0;
var deletedId = 0;

function onDataBinding() {
var grid = $('#DemandGrid').data('kendoGrid');
rowNumber = (grid.dataSource.page() - 1) * grid.dataSource.pageSize();

}

function getRowNumber() {
return ++rowNumber;
}

function getFilter() {
return {
nameFilter: $("#nameFilter").val()
};
}

function getError() {
var url = "@Url.Action("GotError", "Error")";
window.location = url;
}

public ActionResult LoadMachines([DataSourceRequest] DataSourceRequest request, string nameFilter)
{
try
{
var entities = _commonService.GetMachineMasters().Where(t => t.Status != 1);
var planModels = entities.ToDataSourceResult(request, Mapper.Map<MachineMasterView, MachineMasterViewModel>);
return Json(planModels, JsonRequestBehavior.AllowGet);
}
catch (Exception exp)
{
_commonService.SaveLog(exp.ToString());
throw;
}
}

 

20、js修改gird的datasource,column等

$('#CompaniesGrid').data('kendoGrid').dataSource.aggregate([
{ field: "ValueAddedTax", aggregate: "sum" }
]);

$('#CompaniesGrid').data('kendoGrid').setOptions(
{ columns: [{ field: "ValueAddedTax", title: "Product Name" ,aggregates: ["sum"],
footerTemplate: "合计:#=getFormatString(sum)#"
}]
}
);

21、获取筛选排序参数post出去用于导出数据等

var grid = $('#LaborsGrid').data('kendoGrid');
var parameterMap = grid.dataSource.transport.parameterMap;
var sortData = grid.dataSource.sort();
var filterData = grid.dataSource.filter();
var groupData = grid.dataSource.group();
var prepared = parameterMap({ sort: sortData, filter: filterData, group: groupData });
var url = "@Url.Action("ExportData", "EAPostCheck")";
$.post(url, prepared, function() {
window.location = "@Url.Action("GenerateWord", "EAPostCheck")";
});

22、待grid绑定完数据设置高度,避免出现垂直滚动条

.Filterable(x => x.Enabled(false))
.Scrollable(x => x.Enabled(true))
//.Scrollable(scr => scr.Height(350))
.Resizable(resize => resize.Columns(true))
.Events(e => e.DataBinding("onDataBinding").DataBound("onDataBound"))

function onDataBound() {
$("#Grid .k-grid-content").height($("#Grid tbody[role*='rowgroup']")[0].offsetHeight + 30);
}

上一篇:【转】JSP中的JSTL与EL表达式用法及区别


下一篇:文档对象模型DOM通俗讲解