Kendo grid keeps spinning - asp.net-mvc-4

I'm doing something that should be rather simply with a Kendo UI grid. I have the following Javascript in my web page:
<div id="venueSelectGrid"></div>
<script>
$(document).ready(function () {
model.Init();
});
var model = function () {
Init = function () {
gridSelect('#venueSelectGrid', 'VenueID', 'VenueName', 'Venue', 'DataManager/GetVenue');
};
return {
Init: Init
};
}();
</script>
The gridSelect function is defined in another js file as follows:
gridSelect = function (name, idColumnName, descColumnName, descColumnTitle, url) {
$(name).kendoGrid({
autoBind: true,
width: "18em",
height: "16em",
columns: [
{
field: "IsChecked",
title: "<input type='checkbox' name='IsChecked' class='centerCheckbox parentCheckbox' />",
template: "<input type='checkbox' name='IsChecked' class='childCheckbox' />",
headerTemplate: "<input type='checkbox' id='chkSelectAll' onclick='checkAll(this)'/>",
//headerTemplate: "<input type='checkbox' id='chkSelectAll' onclick='checkAll(" + name + ", this)'/>",
width: "2em"
},
{
field: idColumnName
},
{
field: descColumnName,
title: descColumnTitle,
width: "15em"
}
],
dataSource: new kendo.data.DataSource({
transport: {
read: {
url: url,
dataType: "json",
contentType: "application/json"
}
},
serverFiltering: true,
pageSize: 0
}),
//selectable: "row",
scrollable: true,
sortable: false,
reorderable: false,
resizable: false,
columnMenu: false,
}).data("kendoGrid").hideColumn(idColumnName);
};
The data controller shows below executes just fine:
public ActionResult GetVenue()
{
JsonResult jsonResult = Json(_DictionaryRepository.GetVenue("1"), JsonRequestBehavior.AllowGet);
return jsonResult;
}
which returns a nicely instantiated POCO object containing the VenueID and the VenueName.
The problem is when the page displays the Wait spinner displays and keeps going. No data ever appears. Does anyone see what I'm doing wrong here?
Thanks
Carl

Try this:
public ActionResult GetVenue([DataSourceRequest] DataSourceRequest request)
{
JsonResult jsonResult = Json(_DictionaryRepository.GetVenue("1").ToDataSourceResult(request), JsonRequestBehavior.AllowGet);
return jsonResult;
}

Related

Razor Page Datatables.net Ajax Postback

i'm using datatables.net in my razor page and i have a dropdown which postback to change the data in the datatable
below is the code
$(document).ready(function () {
//$("#taskDt").DataTable();
var table = $("#taskDt").DataTable({
paging: true,
responsive: true,
searching: true,
ordering: true,
order: [[1, "asc"]]
});
$("#ddlGroup").change(function(){
var a= $("#ddlGroup Option:Selected").text();
var b= $("#ddlGroup Option:Selected").val();
//alert(b);
//this.form.submit();
$.ajax({
//dataType: 'json',
url: '/page/Index?handler=GET',
type: 'GET',
dataType: "text",
data: { "Id": b },
processing: true,
serverSide: true,
beforeSend: function (xhr) {
xhr.setRequestHeader("XSRF-TOKEN",
$('input:hidden[name="__RequestVerificationToken"]').val());
},
success: function (data) {
console.log(data);
//table.ajax.reload();
$('#taskDt').DataTable().ajax.reload(true)
//$('#taskDt').DataTable().ajax.reload();
},
error: function () {
alert("AJAX Request Failed, Contact Support");
}
});
})
well the data returned is the full html page and i get an error of invalid JSON
and when i set dataType: "JSON" if fails and alerts ajax request failed
any help will be much appreciated.
Here is a demo to show how to update datatable data when dropdown changes:
Model:
public class Test
{
public int Id { get; set; }
public string Name { get; set; }
}
TestDataTable.cshtml:
<select id="ddlGroup">
<option>Choose Id</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
</select>
<table id="taskDt">
<thead>
<tr>
<td>Id</td>
<td>Name</td>
</tr>
</thead>
<tbody></tbody>
</table>
#section scripts{
<link rel="stylesheet" type="text/css" href="https://cdn.datatables.net/1.10.21/css/jquery.dataTables.css">
<script type="text/javascript" charset="utf8" src="https://cdn.datatables.net/1.10.21/js/jquery.dataTables.js"></script>
<script>
var table;
function LoadData() {
table = $("#taskDt").DataTable({
"ajax": {
url: '?handler=GET',
type: 'GET',
processing: true,
serverSide: true,
},
"columns": [
{ "data": "id", "width": "50%" },
{ "data": "name", "width": "50%" },
],
paging: true,
responsive: true,
searching: true,
ordering: true,
order: [[1, "asc"]]
});
}
$(document).ready(function () {
LoadData();
})
$("#ddlGroup").change(function () {
table.ajax.url("?handler=GET&&Id=" + $("#ddlGroup Option:Selected").val()).load();
});
</script>
}
TestDataTable.cshtml.cs(I use fake data to test):
public class TestDataTableModel : PageModel
{
public void OnGet()
{
}
public JsonResult OnGetGet(int? Id)
{
List<Test> l = new List<Test>();
if (Id == null)
{
l = new List<Test> { new Test { Id = 1, Name = "1" }, new Test { Id = 2, Name = "2" },new Test { Id = 3, Name = "3" } };
}
else
{
l = new List<Test> { new Test { Id = Convert.ToInt32(Id), Name = Id+"" }};
}
return new JsonResult(new { draw = 1, recordsFiltered = l.Count(), recordsTotal = l.Count(), data = l });
}
}
result:

Implement Datatables responsive details display with Ajax data

I want to implement Datatable's responsive details with Bootstrap modal but it doesn't work for me. The first thing I noticed is that the "plus-sign" does not appear on the first column of my table. I'm not sure if this is because I'm using ajax data and need additional parameters that the example doesn't show or because I've added an auto number as my first column.
Here is the table HTML:
<table id="users" class="table table-striped table-bordered nowrap" data-conf="#Model.ExtraVM.DialogMsg" data-title="#Model.ExtraVM.DialogTitle" data-btnok="#Model.ExtraVM.Button1" data-btncancel="#Model.ExtraVM.Button2">
<thead>
<tr>
<th>#Model.HeadingVM.Col1</th>
<th>#Model.HeadingVM.Col2</th>
<th>#Model.HeadingVM.Col3</th>
<th>#Model.HeadingVM.Col4</th>
<th>#Model.HeadingVM.Col5</th>
</tr>
</thead>
<tbody></tbody>
</table>
Here is the jquery code:
<script>
$(document).ready(function () {
var t = $("#users").DataTable({
responsive: {
details: {
display: $.fn.dataTable.Responsive.display.modal({
header: function (row) {
var data = row.data();
return 'Details for ' + data[0] + ' ' + data[1];
}
}),
renderer: $.fn.dataTable.Responsive.renderer.tableAll({
tableClass: 'table'
})
}
},
columnDefs: [{
"searchable": false,
"orderable": false,
"targets": 0
}],
order: [[1, 'asc']],
ajax: {
url: "/api/users",
dataSrc: ""
},
columns: [
{
data: "id"
},
{
data: "firstName"
},
{
data: "lastName"
},
{
data: "userName"
},
{
data: "id",
render: function (data) {
return "<a href='#'><i class='fa fa-eye' data-id='" + data + "' data-toggle='modal' data-target='#dataPopup'></i></a> | <a href='#'><i class='fa fa-pencil js-edit' data-id='" + data + "'></i></a> | <a href='#'><i class='fa fa-trash js-delete' data-id='" + data + "'></i></a>";
}
}
]
});
t.on('order.dt search.dt', function () {
t.column(0, { search: 'applied', order: 'applied' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1;
});
}).draw();
$("#users").on("click", ".js-delete", function () {
var btn = $(this);
var confirm = btn.parents("table").attr("data-conf");
var dialogTitle = btn.parents("table").attr("data-title");
var btnOK = btn.parents("table").attr("data-btnOk");
var btnCancel = btn.parents("table").attr("data-btnCancel");
bootbox.dialog({
message: confirm,
title: dialogTitle,
buttons: {
main: {
label: btnCancel,
className: "btn-default",
callback: function () {
var result = "false";
}
},
success: {
label: btnOK,
className: "btn-primary",
callback: function () {
$.ajax({
url: "/api/users/" + btn.attr("data-id"),
method: "DELETE",
success: function () {
btn.parents("tr").remove();
}
});
}
}
}
});
});
});
</script>
}
This is how my tables looks (as you can see, the plus-sign is missing):
Your code seems to be fine. Plus sign only appears when viewing area is small enough and one of the columns become hidden.
There is no setting to force (+) sign to appear but you can use a trick with extra empty column and class none on it which will force column to always be hidden. See Class logic for more details.
See this jsFiddle for code and demonstration.

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>

jqGrid Paging - no ajax call to get next page

I have a page with two jqGrids on it in different elements. When I first load the page, Firebug reports an ajax call to get the first 15 rows as expected, and the pager accurately shows the number of pages and the number of records. However, when I click the arrows on the pager, no ajax call is traced in Firebug, so I am pretty sure that something is not wired correctly. The odd thing is that I have other pages with only one jqGrid and paging works as expected. I have breakpoints in my controller (MVC4) and the initial load hits them just fine and all of the arguments are correct:
#region GetUnManagedMerchants
public JsonResult GetUnManagedMerchants(string id, string sidx, string sord, int page, int rows)
{
return GetSomeMerchants(id, false, sidx, sord, page, rows);
}
#endregion
Here is my script code:
$(document).ready(function () {
jQuery("#grdUnManaged").jqGrid({
url: '/Ajax/GetUnManagedMerchants/' + $('#UserInContext_UserId').val(),
datatype: 'json',
mType: 'GET',
colNames: ['', 'UnManaged Merchant', ''],
colModel: [
{ name: 'Manage', key: true, index: 'manage', width: 20, sortable: false, formatter: function () { return '<img src="#Url.Content("~/content/images/icons/merchant.png")" width="16" height="16" alt="Merchants" />'; } },
{ name: 'Name', index: 'name', width: 325 },
{ name: 'id', index: 'id', width: 0, hidden: true , key: true}
],
pager: '#grdUnManagedPager',
rowNum: 15,
width: 450,
height: 300,
viewrecords: true,
caption: 'Current UnManaged Merchants',
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 0) {
var merchantId = jQuery(this).getRowData(rowid)['id'];
var userId = $('#UserInContext_UserId').val();
ManageMerchant(userId, merchantId);
return true;
}
return false;
}
});
jQuery("#grdUnManaged").jqGrid('navGrid', '#grdUnManagedPager', { add: false, edit: false, del: false, search: false, refresh: true });
});
Please help me with what is missing! This is the last item I need to fix prior to finishing this project.
Thanks!
I have made the changes you suggest (Thanks) yet I still do NOT get an ajax call back when I click on the pager to see a subsequent page. I am re-posting my entire script with both grids.
<script type="text/javascript">
var buttonNames = {};
buttonNames[0] = 'Manage';
$(document).ready(function () {
jQuery('#currentUserHeader').html('<h3>Merchant Lists for ' + $('#UserInContext_Email').val() + '.</h3>');
jQuery("#grdManaged").jqGrid({
url: '/Ajax/GetManagedMerchants/' + $('#UserInContext_UserId').val(),
datatype: 'json',
mType: 'GET',
colNames: ['', 'Managed Merchant', ''],
colModel: [
{ name: 'Manage', index: 'Manage', width: 20, sortable: false, formatter: function () { return '<img src="#Url.Content("~/content/images/chevron.png")" width="16" height="16" alt="Merchants" />'; } },
{ name: 'Name', index: 'Name', width: 325 },
{ name: 'id', index: 'id', width: 0, hidden: true, key: true }
],
pager: '#grdManagedPager',
rowNum: 15,
width: 450,
height: 300,
viewrecords: true,
caption: 'Current Managed Merchants',
beforeRequest: function () {
var getUrl = '/Ajax/GetManagedMerchants/' + $('#UserInContext_UserId').val();
$('#grdManaged').setGridParam([{ url: getUrl }]);
},
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 0) {
var merchantId = jQuery(this).getRowData(rowid)['id'];
var userId = $('#UserInContext_UserId').val();
UnManageMerchant(userId, merchantId);
return true;
}
return false;
}
});
jQuery("#grdManaged").jqGrid('navGrid', '#grdManagedPager', { add: false, edit: false, del: false, search: false, refresh: true });
});
</script>
<script type="text/javascript">
$(document).ready(function () {
jQuery("#grdUnManaged").jqGrid({
url: '/Ajax/GetUnManagedMerchants/' + $('#UserInContext_UserId').val(),
datatype: 'json',
mType: 'GET',
colNames: ['', 'UnManaged Merchant', ''],
colModel: [
{ name: 'Manage', index: 'Manage', width: 20, sortable: false, formatter: function () { return '<img src="#Url.Content("~/content/images/chevron-left.png")" width="16" height="16" alt="Merchants" />'; } },
{ name: 'Name', index: 'Name', width: 325 },
{ name: 'id', index: 'id', width: 0, hidden: true , key: true}
],
pager: '#grdUnManagedPager',
rowNum: 15,
width: 450,
height: 300,
viewrecords: true,
caption: 'Current UnManaged Merchants',
beforeRequest: function () {
var getUrl = '/Ajax/GetUnManagedMerchants/' + $('#UserInContext_UserId').val();
$('#grdUnManaged').setGridParam([{ url: getUrl }]);
},
beforeSelectRow: function (rowid, e) {
var iCol = $.jgrid.getCellIndex(e.target);
if (iCol == 0) {
var merchantId = jQuery(this).getRowData(rowid)['id'];
var userId = $('#UserInContext_UserId').val();
ManageMerchant(userId, merchantId);
return true;
}
return false;
}
});
jQuery("#grdUnManaged").jqGrid('navGrid', '#grdUnManagedPager', { add: false, edit: false, del: false, search: false, refresh: true });
});
may be your jqgrid overrides each other,may be on click paging second jqgrid overrides some thig,,,
but hope this help..
http://www.codeproject.com/Articles/594150/MVC-Basic-Site-Step-4-jqGrid-In

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;
...
...