Datatable.Net - Search by columns is not rendering - asp.net-core

I'm using jQuery datatable.net to render a table (server-side). Everything including filtering is working fine. I elected to implement searching by column and I just can't seem to get it to render the values. When I type in a value, the "Processing" window displays and immediately goes away (which tells me that the search string is being processed) however the search results are not being displayed.
My datatable script is as follows:
#section scripts {
<script type="text/javascript">
$(document).ready(function () {
$('#contacts tfoot th').each(function () {
var title = $(this).text();
$(this).html('<input type="text" placeholder="Search ' + title + '" />');
});
var contactlist = $('#contacts').DataTable({
responsive: true,
destroy: true,
orderMulti: true,
processing: true,
serverSide: true,
stateSave: true,
stateSaveCallback: function (settings, data) {
localStorage.setItem('DataTables_' + settings.sInstance, JSON.stringify(data))
},
stateLoadCallback: function (settings) {
return JSON.parse(localStorage.getItem('DataTables_' + settings.sInstance))
},
oLanguage: {
sSearch: ""
},
pagingType: "full_numbers",
filter: true,
rowId: "id",
order: [[1, "asc"]],
ajax: {
url: "/Contact/GetContactList",
type: "POST",
datatype: "json"
},
columnDefs: [{
targets: [0],
visible: false,
searchable: false
}],
"columns": [
{ data: "id", name: "Id", autoWidth: true},
{ data: "firstName", name: "FirstName", autoWidth: true },
{ data: "lastName", name: "LastName", autoWidth: true },
{ data: "company", name: "Company", autoWidth: true },
{
data: null,
name: "Phone",
autoWidth: true,
defaultContent: "",
render: function (data, type, row) {
var cell = "";
var office = "";
var other = "";
if (row.phoneCell != null) {
cell = "<i class='fas fa-mobile-alt'></i><a href='tel:" + row.phoneCell + "'> " + "<small>" + row.phoneCell + "</small></a>";
}
if (row.phoneOffice != null) {
if (cell != "") { office = "<br />"; }
office = office + "<i class='fas fa-building'></i><a href='tel:" + row.phoneOffice + "'> " + "<small>" + row.phoneOffice + "</small></a>";
}
if (row.phoneOther != null) {
if (office != "") { other = "<br />"; }
other = other + "<i class='fas fa-phone-square-alt'></i><a href='tel:" + row.phoneOther + "'> " + "<small>" + row.phoneOther + "</small></a>";
}
return cell + office + other;
}
},
{
data: "webSite",
name: "WebSite",
autoWidth: true,
defaultContent: "",
render: function (data, type, row) {
if (row.webSite != null) {
return "<i class='fas fa-globe-americas'></i><a href='" + row.webSite + "' target='_blank'> " + "<small>" + row.webSite + "</small></a>";
}
}
},
{ data: "campaign", name: "Campaign", autoWidth: true, defaultContent: "" },
],
initComplete: function () {
var r = $('#contacts tfoot tr');
r.find('th').each(function () {
$(this).css('padding', 8);
});
$('#contacts thead').append(r);
$('#search_0').css('text-align', 'center');
var api = this.api();
api.columns().every(function () {
var that = this;
$('input', this.footer()).on('keyup change', function () {
if (that.search() !== this.value) {
that.search(this.value);
that.draw();
}
});
});
}
});
$('.dataTables_filter input[type="search"]').
attr('placeholder', 'Filter by first/last name or company ...').
css({ 'width': '350px', 'display': 'inline-block' });
$('#contacts tbody').on('click', 'tr', function () {
debugger;
var currentRowData = contactlist.row(this).data();
var id = currentRowData.id;
var url = "#Url.Action("View", "Contact")?id=" + id;
window.open(url,"_parent");
});
});
</script>
Any idea what I'm doing wrong?
Thanks.
-- Val

Related

Reset Vue Bootstrap Table

i am using vue-bootstrap4-table in my application i have a custom input though which i search and populate the data,now i need to build a feature in which their is a cross button inside the search field and on clicking on it it should reset the table to empty state here is my code
<template>
<auto-complete
#autocomplete-result-selected="setCustomer"
placeholder="Enter Customer name"
:selected="selectedCustomer"
:styles="{width: 'calc(100% - 10px)'}"
index="locations"
attribute="name"
>
<template slot-scope="{ hit }">
<span>
{{ hit.customer.company && hit.customer.company + ' - ' }}{{ hit.customer.fname }}
{{ hit.customer.lname }}
</span>
</template>
</auto-complete>
<i class="fas fa-times" #click="clearTable()" v-show="selectedCustomer"></i>
</div>
</div>
</template>
<script>
import http from "../../helpers/api.js";
import AutoComplete from "../autocomplete/Autocomplete";
import axios from "axios";
import VueBootstrap4Table from "vue-bootstrap4-table";
export default {
components: {
"auto-complete": AutoComplete,
VueBootstrap4Table
},
computed: {},
data() {
return {
value: "",
selectedCustomer: "",
selectedFirstName: "",
selectedLastName: "",
selectedFields: [
{ name: "Invoice", value: "invoices" },
{
name: "Estimate",
value: "workorder_estimates"
}
],
filters: [
{ is_checked: true, value: "invoices", name: "Invoice" },
{ is_checked: true, value: "workorder_estimates", name: "Estimate" }
],
selectedFilters: [],
estimateChecked: false,
invoiceChecked: false,
config: {
card_mode: false,
show_refresh_button: false,
show_reset_button: false,
global_search: {
placeholder: "Enter custom Search text",
visibility: false,
case_sensitive: false
},
pagination: true,
pagination_info: false,
per_page: 10,
rows_selectable: true,
server_mode: true,
preservePageOnDataChange: true,
selected_rows_info:true
},
classes: {},
rows: [],
columns: [
{
label: "TYPE",
name: "type"
},
{
label: "ID",
name: "distinction_id"
},
{
label: "CUSTOMER NAME",
name: "full_name"
},
{
label: "SERVICE DATE",
name: "service_date"
},
{
label: "ADDRESS",
name: "address1"
},
{
label: "CREATE DATE",
name: "created_at"
}
],
queryParams: {
sort: [],
filters: [],
global_search: "",
per_page: 10,
page: 1
},
selected_rows: [],
total_rows: 0
};
},
methods: {
onNameSearch() {
this.selectedFilters = ["invoices", "workorder_estimates"];
this.fetchData();
},
clearTable(){
this.rows=[];
console.log(this.config.selected_rows_info);
this.config.selected_rows_info=false;
},
onChangeQuery(queryParams) {
console.log(queryParams);
this.queryParams = queryParams;
this.fetchData();
},
onRowClick(payload) {
console.log(payload);
},
setCustomer(selectedResult) {
this.selectedCustomer = selectedResult.customer.company
? `${selectedResult.customer.company + " - "}${
selectedResult.customer.fname
} ${selectedResult.customer.lname}`
: `${selectedResult.customer.fname} ${selectedResult.customer.lname}`;
this.selectedFirstName = selectedResult.customer.fname;
this.selectedLastName = selectedResult.customer.lname;
},
changeCheck(event, index, value) {
var checked = event.target.checked;
switch (value) {
case "invoices":
if (checked) {
this.selectedFields.push({ name: "Invoice", value: "invoices" });
this.invoiceChecked = true;
var data = this.filters[index];
data.is_checked = true;
Vue.set(this.filters, data, index);
} else {
var index = this.selectedFields.findIndex(
item => item.value === value
);
this.selectedFields.splice(index, 1);
this.invoiceChecked = false;
var data = this.filters[index];
data.is_checked = false;
Vue.set(this.filters, data, index);
}
break;
case "workorder_estimates":
if (checked) {
this.selectedFields.push({
name: "Estimate",
value: "workorder_estimates"
});
var data = this.filters[index];
data.is_checked = true;
Vue.set(this.filters, data, index);
} else {
var index = this.selectedFields.findIndex(
item => item.value === value
);
this.selectedFields.splice(index, 1);
this.estimateChecked = false;
var data = this.filters[index];
data.is_checked = false;
Vue.set(this.filters, data, index);
}
break;
}
},
removeFilter(index, value) {
switch (value) {
case "workorder_estimates":
this.selectedFields.splice(index, 1);
this.estimateChecked = false;
var i = this.filters.findIndex(item => item.value === value);
var data = this.filters[i];
data.is_checked = false;
Vue.set(this.filters, data, i);
break;
case "invoices":
this.selectedFields.splice(index, 1);
this.invoiceChecked = false;
var i = this.filters.findIndex(item => item.value === value);
var data = this.filters[i];
data.is_checked = false;
Vue.set(this.filters, data, i);
break;
}
},
updateFilters() {
this.selectedFilters = [];
this.selectedFields.forEach(element => {
this.selectedFilters.push(element.value);
});
if(this.selectedFilters.length == 0){
this.selectedFilters = ['invoices', 'workorder_estimates'];
}
this.fetchData();
},
async fetchData() {
var final = [];
try {
var result = await http.post("/estimate-invoice-search", {
type: this.selectedFilters,
search: {
value: this.selectedFirstName + " " + this.selectedLastName
},
per_page: this.queryParams.per_page,
page: this.queryParams.page,
sort: this.queryParams.sort
});
this.total_rows = result.recordsFiltered;
result.data.forEach(element => {
element.full_name = element.first_name + " " + element.last_name;
final.push(element);
});
this.rows = final;
} catch (error) {
console.log(error);
}
}
},
mounted() {}
};
</script>
now the method named clearTable here i want to reset my table to the point lie we see on page refresh in the method i used this.rows=[]; this clears all the rows which is exactly what i want but the text which shows the number of rows is still their and i cant seem to remove it please view the below image for clarification
i read the documentation on link but cant seem to find a solution for hiding the text, is their any way?
It looks like you're using total_rows as the variable for the number of rows in your template here:
<span>{{total_rows}}</span> Result(s)
The only spot in code that you set this value is in fetchData() where you set:
this.total_rows = result.recordsFiltered;
You can either:
1) Make total_rows a computed property (recommended) that returns the length of rows (I believe rows is always the same length as total_rows from your code)
-or-
2) Just set this.total_rows = 0; in your clearTable() function

Datatables get value of searchable on a column

I have created a datatable with following code:
userTable = $('#userTable').DataTable({
serverSide: true,
processing: true,
ajax: {
url: "{!! route('listOfUsersAjax') !!}",
type: "GET",
dataSrc: function ( json ) {
//console.log(json);;
for ( var i=0, ien=json.data.length ; i<ien ; i++ ) {
if (json.data[i].is_manager == 1){
json.data[i].is_manager = 'Yes';
}
else {
json.data[i].is_manager = 'No';
}
}
return json.data;
}
},
columns: [
{
className: 'details-control',
orderable: false,
searchable: false,
data: null,
defaultContent: ''
},
{ name: 'id', data: 'id' },
{ name: 'name', data: 'name' },
{ name: 'email', data: 'email' },
{ name: 'is_manager', data: 'is_manager'},
{ name: 'region', data: 'region' },
{ name: 'country', data: 'country' },
{ name: 'domain', data: 'domain' },
{ name: 'management_code', data: 'management_code' },
{ name: 'job_role', data: 'job_role' },
{ name: 'employee_type', data: 'employee_type' },
{
name: 'actions',
data: null,
sortable: false,
searchable: false,
render: function (data) {
var actions = '';
actions += '<div class="btn-group btn-group-xs">';
actions += '<button data-toggle="tooltip" title="view" id="'+data.id+'" class="buttonView btn btn-success"><span class="glyphicon glyphicon-eye-open"></span></button>';
actions += '<button data-toggle="tooltip" title="edit" id="'+data.id+'" class="buttonUpdate btn btn-primary"><span class="glyphicon glyphicon-pencil"></span></button>';
actions += '<button data-toggle="tooltip" title="delete" id="'+data.id+'" class="buttonDelete btn btn-danger"><span class="glyphicon glyphicon-trash"></span></button>';
actions += '</div>';
return actions;
}
}
],
columnDefs: [
{
"targets": [1,3,4], "visible": false, "searchable": false
}
],
order: [[2, 'asc']],
initComplete: function () {
this.api().columns().every(function () {
var column = this;
//console.log(userTable);
// Now we need to skip the first column as it is used for the drawer...
if(column[0][0] == '0' || column[0][0] == '11'){return true;};
var input = document.createElement("input");
$(input).appendTo($(column.footer()).empty())
.on('keyup change', function () {
column.search($(this).val(), false, false, true).draw();
});
});
}
} );
At the end, you can see that I have put a initComplete to have search columns to be at the bottom of each column.
I don't need to have a search when the column is not searchable, for example, first column and last one because it is not searchable. I am using the number of the column and returning true so that it doesn't create it but I would like something more dynamic and have an if column searchable is false then return true that way I don't need to specify the number of the column.
Thanks for your help.
You do have the columns definition available through this.api().init().columns. So all you have to do is to evaluate if a columns searchable explicit is set to false (not defining searchable or not defining the column at all means true, since this is the default) :
initComplete: function() {
var columns = this.api().init().columns;
this.api().columns().every(function(index) {
if (!columns[index] || columns[index].searchable) {
// column is searchable
} else {
// column is not searchable
}
})
}

How to select all checkbox based on custom checkbox in filterTemplate in JsGrid

Here i am trying to check all checkbox for using custom checkbox we can see here filterTemplate section and selectAll or unselectAll these are Bold for getting my point
<script>
$(function () {
$.ajax({
type: "GET",
url: "/MerchandiseList/GetMerchant"
}).done(function (data) {
//$("#leftMenu").hide();
//reloadpage(data);
var MyDateField = function (config) {
jsGrid.Field.call(this, config);
};
MyDateField.prototype = new jsGrid.Field({
sorter: function (date1, date2) {
return new Date(date1) - new Date(date2);
},
itemTemplate: function (value) {
if (value == "")
return "";
else {
var date = new Date(value).toDateString()
//var date = new Date(value).toDateString("MM/dd/yyyy")
//return new Date(value).toDateString();
//return value;
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2) month = '0' + month;
if (day.length < 2) day = '0' + day;
var df = [month, day, year].join('/');
//var df = [year, month, day].join('/');
date = df;
return date;
}
},
insertTemplate: function (value) {
return this._insertPicker = $("<input>").datepicker({ defaultDate: new Date() });
},
editTemplate: function (value) {
if (value == "")
return this._editPicker = $("<input>").datepicker({ defaultDate: new Date() });
else {
return this._editPicker = $("<input>").datepicker().datepicker("setDate", new Date(value));
}
},
insertValue: function () {
if (this._insertPicker.datepicker("getDate") != null)
return this._insertPicker.datepicker("getDate"); //.toISOString("MM/dd/yyyy")
//else
// return this._insertPicker.datepicker("getDate");
},
editValue: function () {
//debugger
if (this._editPicker.datepicker("getDate") != null)
//.toISOString("MM/dd/yyyy")
return this._editPicker.datepicker("getDate");
//return this._editPicker.datepicker("getDate").toISOString();
//else
// return this._editPicker.datepicker("getDate");
}
});
jsGrid.fields.myDateField = MyDateField;
$("#jsGrid").jsGrid({
height: "50%",
width: "100%",
filtering: true,
editing: true,
editButtonTooltip: "Edit",
inserting: true,
sorting: true,
paging: true,
autoload: true,
pageButtonCount: 5,
pageSize: 15,
overflow: scroll,
confirmDeleting: true,
deleteConfirm: "Do you really want to delete the merchandise?",
//refreshtext: "Refresh",
//onRefreshed: function (args) { },
selecting: true,
controller: db,
fields: [
{
**filterTemplate**: function (_, item) { // how to get all grid items here? This return only single item but empty in Filter row.
return $("<input>").attr("type", "checkbox")
.prop("checked", $.inArray(item, selectedItems) > -1)
.on("change", function () {
$(this).is(":checked") ? selectAll(item) : unselectAll(item);
});
},
itemTemplate: function (_, item) {
return $("<input>").attr("type", "checkbox")
.prop("checked", $.inArray(item, selectedItems) > -1)
.on("change", function () {
$(this).is(":checked") ? selectItem(item) : unselectItem(item);
});
},
align: "center",
width: 50,
sorting: false,
filtering: false
},
{ type: "control" },
{
name: "Source", type: "text", width: 120, title: "Vendor"
},
{
name: "Description", type: "text", width: 210,
validate: { message: "Description is required!", validator: function (value) { return value != ""; } }
},
{
name: "ModelNumber", type: "text", width: 120, title: "Model#/Item"
},
{ name: "SKU", type: "text", width: 90 },
{ name: "SKU2", type: "text", width: 90 },
{ name: "Comments", type: "text", width: 200 },
{ name: "strReceiveDate", type: "myDateField", width: 80, align: "center", title: "Received" },
{ name: "Location", type: "select", items: data.loc, valueField: "LocationID", textField: "Description", width: 100 },
{ name: "Barcode", width: 80 },
{ name: "BarcodePrinted", type: "checkbox", title: "Barcode Printed", sorting: false },
//{ name: "strLastUpdatedDate", type: "myDateField", width: 80, title: "Last Updated" },
{ name: "strLastUsedDate", type: "myDateField", width: 80, title: "Last Updated" },
{ name: "DamageCode", type: "select", items: data.dam, valueField: "CodeID", textField: "CodeValue", title: "Damage" },
{ name: "strCreatedDate", editable: false, width: 80, title: "Created Date", type: "myDateField" },
{ name: "strShipDate", type: "myDateField", myCustomProperty: "bar", width: 80, title: "Ship Date" },
{ name: "strConsumeDate", type: "myDateField", myCustomProperty: "bar", width: 80, title: "Consume Date" },
{ name: "PendingShipment", type: "checkbox", title: "Pending", sorting: false, width: 60 },
{ name: "Donated", type: "checkbox", title: "Is Donated", sorting: false, width: 60 },
{ name: "ReturnRequested", type: "checkbox", title: "Return Requested", sorting: false },
{ name: "ReturnTo", type: "text", width: 150, title: "Return To" },
{ name: "Quantity", type: "number", width: 50, title: "Qty" },
{ name: "GroupName", type: "text", width: 150, title: "Group Name" },
{ name: "CustomerID", width: 100, title: "Customer ID" }
],
});
var selectedItems = [];
var selectItem = function (item) {
document.getElementById("hdn").value = document.getElementById("hdn").value + "," + item.Barcode;
selectedItems.push(item);
//debugger
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var unselectItem = function (item) {
selectedItems = $.grep(selectedItems, function (i) {
//debugger
return i !== item;
});
var value = document.getElementById("hdn").value;
value = value.replace(item.Barcode, "");
document.getElementById("hdn").value = value;
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var **selectAll** = function (item) {
document.getElementById("hdn").value = document.getElementById("hdn").value + "," + item.Barcode;
selectedItems.push(item);
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
var **unselectAll** = function (item) {
selectedItems = $.grep(selectedItems, function (i) {
//debugger
return i !== item;
});
var value = document.getElementById("hdn").value;
value = value.replace(item.Barcode, "");
document.getElementById("hdn").value = value;
var $grid = $("#jsGrid");
$grid.jsGrid("option", "editing", false);
$grid.jsGrid("option", "editing", true);
};
});
});
here the output image here [https://i.stack.imgur.com/gMfwn.png][1]
But noting happens can any one help me

How to add a link button in knockout grid using MVC

I am new to knockout and MVC. I wanted to add a link button(delete) which will delete the record that is displayed in my knockout grid. I really dont have any idea how to achieve this. I have the following code that displays the record using the KO grid. Now I want to add a link button in the grid to delete the record
CONTROLLER:
public JsonResult GetResult()
{
GetResultRequest req = new GetResultRequest() { AcctID=57345, PartyType=2 };
var getResultInfo = WSHelper.WsService.GetResults(req);
return Json(getResultInfo.Signers, JsonRequestBehavior.AllowGet);
}
VIEW:
#Styles.Render("~/Content/css")
#Scripts.Render("~/bundles/SafeHarborBundle")
<script src="~/Scripts/koGrid-2.1.1.js"></script>
<script type="text/javascript">
var dataViewModel = ko.mapping.fromJS(#Html.Raw(Json.Encode(Model)));
<div id="gridSigner">
<div id="grids123" style="height: 700px; width: 650px;"
data-bind="koGrid: {
data: gridItems, columnDefs: [{ field: 'AcctID', displayName: 'AcctID', width: '150' },
{ field: 'FName', displayName: 'First Name', width: '150' },
{ field: 'LName', displayName: 'Last Name', width: '150' },
{ field: 'AliasFName', displayName: 'Alias First Name', width: '150' },
{ field: 'SSN', displayName: 'AcctID', width: '150' }],
autogenerateColumns: false,
isMultiSelect: false,
showFilter: true,
showColumnMenu: true,
enablePaging: false,
displaySelectionCheckbox: false,
enableColumnResize: false,
multiSelect: false
}">
JQUERY FILE:
$(document).ready(function () {
loadApplication(dataViewModel);
ko.applyBindings(Gridviews, document.getElementById('gridSigner'));
});
function loadApplication(initialData) {
self = this;
self.ViewModel = initialData;
self.BranchOptions = ko.observableArray([]);
self.AcctTypeOptions = ko.observableArray([]);
self.OriginationOptions = ko.observableArray([]);
self.Message = ko.observable();
SearchSignerData();
ko.applyBindings(self, document.getElementById('main-search'));
}
SearchSignerData = function () {
$.ajax({
type: "Get",
url: "/SafeHarborApp/GetResult",
contentType: 'application/json',
async: true,
cache: false,
beforeSend: function () {
},
success: function (result) {
alert(result[0].AcctID.toString());
if (result.length != 0) {
$.each(result, function (i, item) {
Gridviews.gridItems.push(item);
});
}
else {
Gridviews.gridItems.removeAll();
alert("No Records found");
}
},
complete: function () {
},
error: function (xhr, textStatus, errorThrown) {
//alert(jqXHR.responseText);
var title = xhr.responseText.split("<title>")[1].split("</title>")[0];
alert(title);
// Handle error.
}
});
}
The above code works fine in displaying the record in the KO grid. However, I dont know how to add a delete button in the displayed KO grid now. I tried searching for it but was not able to find anything useful that will get me the result. Please help...
Use CellTemplate in ko grid.plese see code below
<script type="text/javascript">
self.NoOfAccountColumn = '<a data-bind="value: $parent.entity" onclick="Popup(this.value)">No Of Account</a>';
self.Delete = '<a data-bind="value: $parent.entity" onclick="deleteRow(this.value)">Delete</a>';
function Popup(rowItem) {
alert(rowItem.AffinityNum + ' ' + rowItem.ClientName + ' : NoOfAccount Clicked');
}
function deleteRow(rowItem) {
alert(rowItem.AffinityNum + ' ' + rowItem.ClientName + ' : Delete Clicked');
}
function isDoubleClick(oldValue, currentValue) {
var responseTime = 400;
if ((currentValue - oldValue) <= responseTime) {
self.clickTime = currentValue;
return true;
}
self.clickTime = currentValue;
return false;
};
</script>
<script src="~/Scripts/Packages/koGrid-2.1.1.js"></script>
<div id="disp">
<div id="grid" style="height: 200px; width: 600px"
data-bind="koGrid: {
data: BranchOptions,
afterSelectionChange: function (rowItem, event) {
if (event.type == 'click' && isDoubleClick(self.clickTime, event.timeStamp)) {
alert(rowItem.entity.ClientName + ' : Row DoubleClick');
}
},
columnDefs: [{ field: 'ClientName', displayName: 'Client Name', width: '*', },
{ field: 'AffinityNum', displayName: 'Affinity Num', width: '*', cellTemplate: NoOfAccountColumn },
{ field: 'AffinityID', displayName: 'Affinity ID', width: '*', cellTemplate: Delete }],
autogenerateColumns: false,
isMultiSelect: false,
showFilter: true,
showColumnMenu: true,
enablePaging: false,
displaySelectionCheckbox: false,
enableColumnResize: true,
multiSelect: false
}">
</div>
</div>

How to bind .Url(Url.Action()) property to toolbar in kendo ui grid(html)

i have a grid developed using kendo ui and asp.net mvc4 razor.in there i have used the html syntax for kendo grid instead of asp.net mvc.
this is the code of my grid
<div id="example" class="k-content">
<div id="batchgrid">
</div>
</div>
<script type="text/javascript" lang="javascript">
$("#batchGrid").click(function () {
var crudServiceBaseUrl = "http://demos.kendoui.com/service",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: crudServiceBaseUrl + "/Products",
dataType: "jsonp"
},
update: {
url: crudServiceBaseUrl + "/Products/Update",
dataType: "jsonp"
},
destroy: {
url: crudServiceBaseUrl + "/Products/Destroy",
dataType: "jsonp"
},
create: {
url: crudServiceBaseUrl + "/Products/Create",
dataType: "jsonp"
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
}
},
batch: true,
pageSize: 20,
schema: {
model: {
id: "ProductID",
fields: {
ProductID: { editable: false, nullable: true },
ProductName: { validation: { required: true} },
UnitPrice: { type: "number", validation: { required: true, min: 1} },
UnitsInStock: { type: "number", validation: { min: 0, required: true} },
Discontinued: { type: "boolean" },
TotalStock: { type: "number" }
}
}
},
// group: {
// field: "UnitPrice", aggregates: [
// { field: "UnitPrice", aggregate: "sum" },
// { field: "TotalStock", aggregate: "sum" }
// ]
// },
aggregate: [{ field: "TotalStock", aggregate: "sum"}]
});
$("#batchgrid").kendoGrid({
dataSource: dataSource,
dataBound: onDataBound,
navigatable: true,
filterable: {
messages: {
and: "And",
or: "Or",
filter: "Apply filter",
clear: "Clear filter",
info: "Filter by"
},
extra: false, //do not show extra filters
operators: { // redefine the string operators
string: {
contains: "Contains",
doesnotcontain: "Doesn't contain",
startswith: "Starts With",
endswith: "Ends"
},
number: {
eq: "Is Equal To",
neq: "Not equal to",
gte: "Greater than or equal to",
lte: "Less than or equal to",
gt: "Greater than",
lt: "Less than"
}
}
},
reorderable: true, //not working
selectable: "multiple",
pageable: {
refresh: true,
pageSizes: [5, 10, 20, 50, 100]
},
height: 430,
width: 300,
toolbar: [
{
name: "my-create",
text: "Add new record"
},
{
name: "save",
text: "save changes"
},
{
name: "cancel",
text: "cancel changes"
},
{
name: "export",
text: "Export To Excel"
}
],
columns: [
// { field: "ProductID", title: "No", width: "90px" },
{title: "No", template: "#= ++record #", width: 45 },
{ field: "ProductName", title: "Product Name", width: "350px" },
{ field: "UnitPrice", title: "Unit Price", format: "{0:c}", width: "130px" },
{ field: "UnitsInStock", title: "Units In Stock", width: "150px" },
{ field: "Discontinued", title: "Purchase", width: "110px" },
{ field: "TotalStock", title: "Total Stock", width: "150px", footerTemplate: "Total : #= kendo.toString(sum, 'C') #", format: "{0:c2}" }
//{ command: ["destroy"], title: " ", width: "175px" }
],
export: {
cssClass: "k-grid-export-image",
title: "people",
createUrl: "/Home/ExportToExcel",
downloadUrl: "/Home/GetExcelFile"
},
groupable: {
messages: {
empty: "Drop columns here"
}
}, //not working
columnMenu: {
sortable: true,
filterable: true,
messages: {
columns: "Hide/Show Columns",
filter: "Apply filter",
sortAscending: "Sort (asc)",
sortDescending: "Sort (desc)"
}
},
resizable: true,
dataBinding: function () {
record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
},
sortable: {
mode: "multiple"
},
sort: { field: "ProductID", dir: "asc" },
editable: { mode: "incell", createAt: "bottom" }
});
//custom global variables
newRowAdded = false;
checkedOnce = false;
var grid = $("#batchgrid").data("kendoGrid");
$(".k-grid-my-create", grid.element).on("click", function (e) {
window.newRowAdded = true;
var dataSource = grid.dataSource;
var total = dataSource.data().length;
dataSource.insert(total, {});
dataSource.page(dataSource.totalPages());
grid.editRow(grid.tbody.children().last());
});
grid.bind("saveChanges", function () {
window.newRowAdded = false;
// var grid = $("#batchgrid").data("kendoGrid");
// grid.dataSource.sort({ field: "ProductID", dir: "asc" });
// GetValOf();
// var grid = $('#batchgrid').data("kendoGrid");
// var total = 0;
// $.each(grid.dataSource.view(), function () {
// total += this.TotalStock;
// });
// alert(total);
});
grid.bind("cancelChanges", function () {
window.newRowAdded = false;
});
$(".k-grid-export", "#batchgrid").bind("click", function (ev) {
// your code
// alert("Hello");
var grid = $("#batchgrid").data("kendoGrid");
grid.dataSource.pageSize(parseInt($("#batchgrid").data("kendoGrid").dataSource.data().length));
excelImport();
});
});
</script>
but i got some example code for importing grid data to excel and in there they used asp.net mvc syntax.
here is the code.
#(
Html.Kendo().Grid(Model).Name("Grid")
.DataSource(ds => ds.Ajax()
.Model(m =>
{
m.Id(p=>p.ProductID);
})
.Read(r => r.Action("Read", "Home"))
)
.ToolBar(toolBar =>
toolBar.Custom()
.Text("Export To Excel")
.HtmlAttributes(new { id = "export" })
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
)
.Columns(columns =>
{
columns.Bound(p => p.ProductID);
columns.Bound(p => p.ProductName);
columns.Bound(p => p.UnitPrice).Format("{0:c}");
columns.Bound(p => p.QuantityPerUnit);
})
.Events(ev => ev.DataBound("onDataBound"))
.Pageable()
.Sortable()
.Filterable()
)
but my problem is i need to add below line of code to my grid(in first code mentioned above).
.ToolBar(toolBar =>
toolBar.Custom()
.Text("Export To Excel")
.HtmlAttributes(new { id = "export" })
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
)
but im stucked with this single line
.Url(Url.Action("Export", "Home", new { page = 1, pageSize = "~", filter = "~", sort = "~" }))
can somebody please tell me that how to use this code in my html grid..
Write Toolbar manual
<div class="k-toolbar k-grid-toolbar k-grid-top">
<a class="k-button k-button-icontext " id="exportCsv" href="/Home/ExportToCsv?take=50&skip=0&page=1&pageSize=10&filter=~&sort=" id="exportToCSV"><span></span>Export CSV</a>
<a class="k-button k-button-icontext " id="exportXls" href="/Home/ExportToXls?take=50&skip=0&pageSize=10&filter=~&sort=" id="exportToExcel"><span></span>Export Excel</a>
</div>
then add databound to kendoGrid
....
editable: false, // enable editing
sortable: true,
filterable: true,
scrollable: false,
dataBound: onDataBound,
columns: [.....
then write 'onDataBound' function
<script>
function onDataBound(e) {
var grid = $('#grid').data('kendoGrid');
var take = grid.dataSource.take();
var skip = grid.dataSource.skip();
var page = grid.dataSource.page();
var sort = grid.dataSource.sort();
var pageSize = grid.dataSource.pageSize();
var filter = JSON.stringify(grid.dataSource.filter());
// Get the export link as jQuery object
var $exportLink = $('#exportXls');
// Get its 'href' attribute - the URL where it would navigate to
var href = $exportLink.attr('href');
// Update the 'take' parameter with the grid's current page
href = href.replace(/take=([^&]*)/, 'take=' + take || '~');
// Update the 'skip' parameter with the grid's current page
href = href.replace(/skip=([^&]*)/, 'skip=' + skip || '~');
// Update the 'page' parameter with the grid's current page
href = href.replace(/page=([^&]*)/, 'page=' + page || '~');
// Update the 'sort' parameter with the grid's current sort descriptor
href = href.replace(/sort=([^&]*)/, 'sort=' + sort || '~');
// Update the 'pageSize' parameter with the grid's current pageSize
href = href.replace(/pageSize=([^&]*)/, 'pageSize=' + pageSize);
//update filter descriptor with the filters applied
href = href.replace(/filter=([^&]*)/, 'filter=' + (filter || '~'));
// Update the 'href' attribute
$exportLink.attr('href', href);
$('#exportCsv').attr('href', href.replace('ExportToXls', 'ExportToCsv'));
}
</script>
And this is the Action, and parameters
public FileResult ExportToXls(int take, int skip, IEnumerable<Sort> sort, string filter)
{
try
{
Filter objfilter = JsonConvert.DeserializeObject<Filter>(filter);
var lstContactFormData = XmlData.GetIletisimBilgileri().OrderByDescending(i => i.tarih);
//Get the data representing the current grid state - page, sort and filter
//IEnumerable products = _db.Products.ToDataSourceResult(request).Data;
IEnumerable contactsDatas = lstContactFormData.AsQueryable().ToDataSourceResult(take, skip, sort, objfilter).Data;
...
...