Is there any option for jqGrid row ordering by drag and drop ? I would like to save the order in DB. I have checked all existing solutions relatedto jqGrid drag & drop. But, nothing is working properly.
Here is my approach with ASP.NET MVC. But you should know that this easy to implement only if you don't have pager.
The main idea is to get all ids in your grid after drop and change item_order in your DB.
HTML
<table id="jqgTopMenu" cellpadding="0" cellspacing="0"></table>
<div id="jqgpTopMenu" style="text-align: center;"></div>
Script
$('#jqgTopMenu').jqGrid({
url: '#Url.Action("TopMenus")',
datatype: 'json',
mtype: 'POST',
colNames: ['Id', 'ItemOrder', 'Name', 'Short name'],
colModel: [
{ name: 'Id', index: 'Id', hidden: true },
{ name: 'ItemOrder', index: 'ItemOrder', hidden: true },
{ name: 'PostName', index: 'PostName', align: 'left', width: 430 },
{ name: 'PostNameShort', index: 'PostNameShort', align: 'left', width: 500 },
],
});
//sort Part
$('#jqgTopMenu').jqGrid('sortableRows',
{
update: function (e, ui) {
var ids = $("#jqgTopMenu").jqGrid('getDataIDs');
$.ajaxSettings.traditional = true;
$.ajax({
url: '#Url.Action("SortTopMenu","Admin")',
type: 'post',
dataType: 'json',
data: { ids: ids },
success: function (data) {
$('#jqgTopMenu').trigger("reloadGrid")
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
console.log("status: " + textStatus + " Error: " + errorThrown);
}
});
}
});
Controller
[HttpPost]
public JsonResult SortTopMenu(List<int> ids)
{
return Json(_dataManager.TopMenu.Sort(ids));
}
Manager DB method
public bool Sort(List<int> ids)
{
for (int i = 0; i < ids.Count; i++)
{
top_menu t = _dataContext.top_menu.FirstOrDefault(tm => tm.id == ids[i]);
t.item_order = i;
_dataContext.SubmitChanges();
}
return true;
}
Related
I am a new Software Developer. In my new company, I use their framework to code. And its using Kendo. I tried to make a search field for Kendo Grid so I can find a specific information in that grid. I tried this method but it doesn't work. Honestly, I don't understand how to use 'transport' things. I call an API to get datas for my grid and I call it in my grid's line of code.
{
type: 'panel',
fields: [{
type: 'panel',
text: 'Payment List',
name: 'payment',
fields: [{
type: 'grid',
name: 'paymentGrid',
data: [],
toolbar: function () {
return `<div class="toolbar" style="width:370px">
<label class="search-label" for="search-reservation" style="color:white"> Cari berdasarkan No. Pesanan: </label>
<input type="search" id="search-reservation" class="search-class">
</div>`
},
sourceOptions: {
pageSize: 10
},
options: {
selectable: true,
autoheight: true,
allowCopy: true,
altrows: true,
pageable: {
refresh: true,
buttonCount: 5,
pageSizes: [10, 20, 50, 100]
},
dataBinding: function () {
record = (this.dataSource.page() - 1) * this.dataSource.pageSize();
}
},
url: function (option) {
var arg = option.data
$.ajax({
method: 'POST',
url: APILink,
data: JSON.stringify(arg),
dataType: 'json',
contentType: 'application/json',
}).done(function (resp) {
if (resp.data != null) {
var nameMap = [];
$.each(resp.data, function (key, val) {
nameMap.push({
id: val.id,
supplier: val.supplier,
reservation_id: val.reservation_id,
currentPayment: val.state
});
});
option.success({
data: nameArray,
total: resp.total
});
}
}).fail(function (jqXHR, status, err) {
option.error(err);
});
},
fields: [{
name: 'number',
text: 'No. ',
template: "#= ++record #",
width: 70,
}, {
name: 'supplier',
text: 'Supplier',
}, {
name: 'reservation_id',
text: 'No. Reservation',
}, {
name: 'currentPayment',
text: 'status',
}, {
name: 'checked',
text: 'choose',
width: 100,
template: function (item) {
return !!item.checked
? `<input id="${item.id}" name='ceklis-boks[]' class="check" checked value="${item.id}" type=\'checkbox\' />`
: `<input id="${item.id}" name='ceklis-boks[]' class="check" value="${item.id}" type=\'checkbox\' />`
}
}],
onDataBound: 'dataBound',
}]
}
Then I used the same code as I mention before in previous link, and replace the ID (#) in that code with mine. But, it won't work. I come to his fiddle and I thought it was because his PlainDs variable and $("#category").kendoAutoComplete({...}) or serverPaging, serverSorting, or serverFiltering. So, I comment all of it here and still working properly. So basically, I can just write the code from line 49 - 81 like in his post. But why it doesn't work? For your information, I call the grid with its name or sometimes I give it a class. But it won't work. Is it a problem if I use class or name instead of ID?
The term "Not working" is too broad here, if you can be more specific on what is not working, we may be able to pinpoint better. However I assume you know how to get the grid to display and so on. so basically to get the search to work I usually have this in the click event of my "Search" button:
var grid = $("#myGrid").data("kendoGrid");
var ds = grid.dataSource;
var searchVal = $("#search-reservation").val();
if ( searchVal ) {
ds.filter({
field: "reservation_id", operator: "eq", value: searchVal
});
}
else {
ds.filter({});
}
I have a Treeview. On selecting the edit of the treenode a kendo grid for Roles will be displayed and few textboxes (where is edit other properties for roles). The kendo grid for roles have checkboxes and Rolenames. My current code is working if I select one checkbox.
What I need is how I get the array of the ids of the roles if I check multiple checkboxes. Tried multiple ways but I am not getting the list of ids when multiple checkboxes are selected. On click edit of the node EditNode is triggered and on click of save the 'click' is trigerred.
Below is my code:
function editNode(itemid) {
var editTemplate = kendo.template($("#editTemplate").html());
var treeview = $("#treeview").data("kendoTreeView");
var selectedNode = treeview.select();
var node = treeview.dataItem(selectedNode);
$("<div/>")
.html(editTemplate({ node: node }))
.appendTo("body")
.kendoWindow({
title: "Node Details",
modal: true,
open: function () {
console.log('window opened..');
editDS = new kendo.data.DataSource({
schema: {
data: function (response) {
return JSON.parse(response.d); // ASMX services return JSON in the following format { "d": <result> }.
},
model: {// define the model of the data source. Required for validation and property types.
id: "Id",
fields: {
Id: { editable: false, nullable: false, type: "string" },
name: { editable: true, nullable: true, type: "string" },
NodeId: { editable: false, nullable: false, type: "string" },
}
},
},
transport: {
read: {
url: "/Services/MenuServices.asmx/getroles",
contentType: "application/json; charset=utf-8", // tells the web service to serialize JSON
type: "POST", //use HTTP POST request as the default GET is not allowed for ASMX
datatype: "json",
},
}
});
rolesGrid = $("#kgrid").kendoGrid({
dataSource: editDS,
height: 150,
pageable: false,
sortable: true,
binding: true,
columns: [
{
field: "name",
title: "Rolename",
headerTemplate: '<span class="tbl-hdr">Rolename</span>',
attributes: {
style: "vertical-align: top; text-align: left; font-weight:bold; font-size: 12px"
}
},
{
template: kendo.template("<input type='checkbox' class = 'checkbox' id='chkbx' data-id='#:Id #' />"),
attributes: {
style: "vertical-align: top; text-align: center;"
}
},
],
}).data('KendoGrid');
},
})
.on("click", ".k-primary", function (e) {
var dialog = $(e.currentTarget).closest("[data-role=window]").getKendoWindow();
var textbox = dialog.element.find(".k-textbox");
var LinKLabel = $('#LL').val();
var roles = $(chkbx).data('roleid');
console.log(PageLocation);
node.text = undefined;
node.set("LINK_LABEL", LinKLabel);
node.set("Roles", roles);
dialog.close();
var treenode = treeview.dataSource.get(itemid);
treenode.set("LINK_LABEL", LinKLabel);
treenode.set("id", Id);
treenode.set("roles", roles);
treenode.LINK_LABEL = LinKLabel;
treenode.ID = Id;
treenode.roles = roles;
var rid = $(chkbx).data('roleid');
$.ajax({
url: "/Services/MenuServices.asmx/UpdateTreeDetails",
contentType: "application/json; charset=utf-8",
type: "POST",
datatype: "json",
data: JSON.stringify({ "Json": treenode })
});
console.log(JSON.stringify(treenode));
})
}
I'm assuming you want to get those ids in this line:
var roles = $(chkbx).data('roleid');
Right? What I don't know is the format you want to get that data. With the following code you can get the roles data in an array objects like this { id: 1, value: true }, check it out:
var grid = $("#grid").data("kendoGrid"),
ids = [];
$(grid.tbody).find('input.checkbox').each(function() {
ids.push({
id: $(this).data("id"),
value: $(this).is(":checked")
});
});
Demo. Anyway you want it, you can change it inside the each loop.
Update:
To get only the checked checkboxes, change the selector to this:
$(grid.tbody).find('input.checkbox:checked')
Demo
Hi i'm trying to add csrf token in post while deleting record in jtable its not working but listAction & updateAction is working fine.
My Code snippets :-
$(document).ready(function () {
$('#main-content').jtable({
title: ' Data',
selecting: true, //Enable selecting
multiselect: true, //Allow multiple selecting
selectingCheckboxes: true, //Show checkboxes on first column
paging: true, //Enable paging
pageSize: 10, //Set page size (default: 10)
actions: {
listAction:"${pageContext.request.contextPath}/mycontroller/all" ,
// createAction:"${pageContext.request.contextPath}/mycontroller/create",
updateAction:"${pageContext.request.contextPath}/mycontroller/edit",
deleteAction:"${pageContext.request.contextPath}/mycontroller/delete"
},
fields: {
code: {
title:'Code',
width: '25%',
key: true,
edit:true,
input: function (data) {
if (data.value) {
return '<input type="text" readonly class="jtable-input-readonly" name="code" value="' + data.value + '"/>';
}
},
},
name: {
title: 'Name',
width: '25%',
create:true,
edit:true
},
craetedTs: {
title: 'Created',
width: '25%',
edit:false
},
modifiedTs: {
title: 'mdate',
width: '25%',
edit:true,
input: function (data) {
if (data.value) {
mdate='';
var date = new Date();
var options = {
year: "numeric", month: "2-digit",
day: "2-digit", hour: "2-digit", minute: "2-digit" ,second:"2-digit"
};
today=date.toLocaleTimeString("en-us", options);
today=today.replace(',', '');
return '<input type="text" readonly class="jtable-input-readonly" name="modifiedTs" value="' + today + '"/>';
}
}
},
_csrf: {
visibility: 'hidden',
edit:true,
input: function (data) {
return '<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}" />';
}
}
}
});
$('#main-content').jtable('load',{'${_csrf.parameterName}' : '${_csrf.token}'});
//Delete selected
$('#DeactiveID').button().click(function () {
var $selectedRows = $('#main-content').jtable('selectedRows');
$('#main-content').jtable('deleteRows', $selectedRows);
});
});
Even i tried for deleting code bellow:-
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
data: '${_csrf.parameterName}' + "=" +'${_csrf.token}' ,
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
But when i checked delete action url the entire method was reflecting
Add meta elements to the page you are invoking the ajax method from
<meta name="_csrf" content="${_csrf.token}"/>
<meta name="_csrf_header" content="${_csrf.headerName}"/>
And make this change to your deleteAction
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
var token = $("meta[name='_csrf']").attr("content");
var header = $("meta[name='_csrf_header']").attr("content");
$.ajax({
url: '/Demo/DeleteStudent',
type: 'POST',
dataType: 'json',
beforeSend: function (request)
{
request.setRequestHeader(header, token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
If somebody is still wondering, Lalit got me going in the right direction, but my final solution is this:
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
This solves the issue with passing csrf, or any additional data, for that matter, in jTable AJAX delete call. As for the other cases. Putting this right after you include the jTable js foxes the initial load:
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
And then there is this hidden field to add to the field list:
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
Here is my code as a full example:
<!-- Include jTable script file. -->
<script src="{{site.uri.public}}/jtable/jquery.jtable.js" type="text/javascript"></script>
<script type="text/javascript">
var csrf_token = $('meta[name=csrf_token]').attr("content");
$.extend(true, $.hik.jtable.prototype.options, {
ajaxSettings: {
data: {csrf_token: csrf_token},
}
});
</script>
<script type="text/javascript">
$(document).ready(function () {
var csrf_token = $('meta[name=csrf_token]').attr("content");
$("#PrizesTableContainer").jtable({
title: 'Prizes',
actions: {
listAction: 'prizes/get',
createAction: 'prizes/create',
updateAction: 'prizes/update',
deleteAction: function (postData) {
return $.Deferred(function ($dfd) {
postData.csrf_token = csrf_token;
$.ajax({
url: 'prizes/delete',
type: 'POST',
dataType: 'json',
data: postData,
beforeSend: function (request)
{
request.setRequestHeader("csrf_token", csrf_token);
},
success: function (data) {
$dfd.resolve(data);
},
error: function () {
$dfd.reject();
}
});
});
}
},
fields: {
id: {
key: true,
list: false
},
machine_name: {
title: 'Machine name',
width: '10%'
},
reel1: {
title: 'Reel1',
width: '15%'
},
reel2: {
title: 'Reel2',
width: '15%'
},
reel3: {
title: 'Reel3',
width: '15%'
},
payout_credits: {
title: 'Payout credits',
width: '15%'
},
payout_winnings: {
title: 'Payout winnings',
width: '15%'
},
probability: {
title: 'Probability',
width: '15%'
},
csrf_token: {
visibility: 'hidden',
edit:true,
input: function (data) {
return "<input type='hidden' name='csrf_token' value='" + csrf_token + "'/>";
}
}
}
});
$("#PrizesTableContainer").jtable('load');
});
</script>
For some reasons I cannot use MVC-wrapper of Kendo grid. So I am trying to build Kendo grid on JavaScript.
There are 2 main problems when trying to update or create records on grid.
1-)All operations(destroy,update,create) on grid just go to create action by Datasource's of Kendo grid. For example after update a record, datasource send data to this URL to many times(number of columns):
http://localhost:63186/Administrator/DefinitionDetailCreate. It should pass values to:
http://localhost:63186/Administrator/DefinitionDetailUpdate
2-)After operation(update or create) Grid sends all data to Action Method instead of new or updated data. So it sends requests the number of columns on grid
JavaScript:
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
data: {DefinitionCode: code},
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")',
type: "POST",
dataType: "text"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "text",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "text",
}
},
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: {editable: false, nullable: true},
DESCRIPTION: {validation: {required: true}}
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: {style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{command: ["edit", "destroy"], title: "Operasyon", width: "100px"}],
editable: "popup"
});
Controller:
[HttpPost]
public ActionResult DefinitionDetailUpdate(Guid ID,Guid REFERENCEID,string DESCRIPTION)
{
return null;
}
[HttpPost]
public ActionResult DefinitionDetailCreate(Guid ID, Guid REFERENCEID, string DESCRIPTION)
{
return null;
}
First you might need to add parameterMap, this will help identify server side methods:
parameterMap: function (options, operation) {
var out = null;
switch (operation) {
case "create":
out = '{ "param":' + options.somevalue + '}';
break;
case "read":
out = '{ "id":' + options.somevalue + '}';
break;
case "update":
out = '{ "id":' + options.somevalue + '}';
break;
case "destroy":
out = '{ "id": ' + options.somevalue + '}';
break;
}
return out;
}
I would also suggest to keep all the dataTypes as dataType: "json"
Also you seem to be missing contentType in your transports definitions :
update: {
url: _op.serviceBaseUrl + "Update",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
complete: function (jqXhr, textStatus) {
}
},
i have posted answer for the same type of question, you may have a check
or
you may Use this code
js
var dataItem = this.dataItem($(e.target).closest("tr"));
var code = dataItem.CODE;
// alert(code);
var crudServiceBaseUrl = "/Administrator/",
dataSource = new kendo.data.DataSource({
transport: {
read: {
url: '#Url.Action("DefinitionDetailRead", "Administrator")',
type: "POST",
dataType: "json"
},
update: {
url: '#Url.Action("DefinitionDetailUpdate", "Administrator")' ,
type: "POST",
dataType: "json"
},
destroy: {
url: '#Url.Action("DefinitionDetailDelete", "Administrator")',
type: "POST",
dataType: "json",
},
create: {
url: '#Url.Action("DefinitionDetailCreate", "Administrator")',
type: "POST",
dataType: "json",
},
parameterMap: function (options, operation) {
if (operation !== "read" && options.models) {
return { models: kendo.stringify(options.models) };
}
} },
// batch: true,
pageSize: 9,
schema: {
data: "Data",
model: {
ID: "ID",
fields: {
ID: { editable: false, nullable: true },
DESCRIPTION: { validation: { required: true } }
}
}
}
});
$("#detailsGrid").kendoGrid({
dataSource: dataSource,
attributes: { style: "padding-left: 0px; font-size: 14px"},
pageable: {refresh: false, pageSizes: false, buttonCount: 5},
toolbar: ["create"],
columns: [
{field: "DESCRIPTION", title: "DESCRIPTION", width: "200px"},
{ command: ["edit", "destroy"], title: "Operasyon", width: "100px" }],
editable: "popup"
});
Controller
[HttpPost]
public ActionResult DefinitionDetailUpdate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
[HttpPost]
public ActionResult DefinitionDetailCreate(string models)
{
//Deserialize to object
IList<UrObjectType> objName= new JavaScriptSerializer().Deserialize<IList<UrObjectType>>(models);
return Json(objName)
}
Note that parameterMap: function() send updated data in serialize string format with name models so you should use "models" as parameter name in your action
i hope this will help you:)
I am trying to "filter" a grid based on an option selected from a select drop down.
How do I send the selected option value to the grid when the change event on the select dropdown fires?
My grid datasource is:
dataSourceParts = new kendo.data.DataSource({
serverPaging: false,
serverFiltering: false,
serverSorting: false,
transport: {
read: {
url: ROOT + 'shipment/partsSerialGrid',
dataType: 'json',
type: 'POST',
data: {
enquiryId: enquiryId
}
}
},
pageSize: 25,
error: function(e) {
alert(e.errorThrown + "\n" + e.status + "\n" + e.xhr.responseText);
},
schema: {
data: "data",
total: "rowcount",
model: {
id: 'id',
fields: {
quantity: {
type: 'number',
editable: false
},
idealForm: {
type: 'string',
editable: false
},
serial: {
type: 'string',
editable: true
}
}
}
}
})
My select event:
$('#fromNameSelect').change(function() {
var fromMode = $('#fromSelect').val();
if (fromMode == 2)
{
supplierId = $(this).val();
dataSourceParts.filter({
field: 'test', operator: 'eq', value: 'test' // THIS DOES NOTHING.
});
$('#shippingPartsGrid').data('kendoGrid').dataSource.read();
}
})
I cant confirm this. But since you set filter in dataSourceParts. Shouldn't you be using dataSourceParts.read() instead of $('#shippingPartsGrid').data('kendoGrid').dataSource.read();?
$('#fromNameSelect').change(function() {
var fromMode = $('#fromSelect').val();
if (fromMode == 2)
{
supplierId = $(this).val();
$('#shippingPartsGrid').data('kendoGrid').dataSource.filter({
field: 'test', operator: 'eq', value: 'test' // DO IT LIKE THIS
});
}
})