Add/edit/delete in jqGrid with Web API - javascript

I am new to jqGrid and need some help on form add/edit/delete functionality. Havent found any relevant resources so far. My grid is displaying pop up on add/edit, also populating data on clicking edit, however I am not sure what should be javascript code to invoke the Web api to POST/PUT/DELETE the data.
Details below:
JSON data:
[{"Id":1,"BankId":2,"BankName":"State bank","EmployeeId":2539,"EmployeeName":"John C.","JoiningDate":"2005-07-05T00:00:00","SalaryAmount":50000.0,"Comments":""},
{"Id":2,"BankId":2,"BankName":"State bank","EmployeeId":2232,"EmployeeName":"xxx","JoiningDate":"2001-12-23T00:00:00","SalaryAmount":30000.0,"Comments":"test"},
{"Id":3,"BankId":4,"BankName":"National bank","EmployeeId":2322,"EmployeeName":"yyyy","JoiningDate":"2002-09-23T00:00:00","SalaryAmount":90000.0,"Comments":""},
{"Id":4,"BankId":3,"BankName":"Punjab bank","EmployeeId":2432,"EmployeeName":"ppp","JoiningDate":"2003-01-31T00:00:00","SalaryAmount":60000.0,"Comments":" "},
{"Id":5,"BankId":1,"BankName":"Bank of Maharashtra","EmployeeId":2892,"EmployeeName":"zzz y.","JoiningDate":"2000-10-11T00:00:00","SalaryAmount":80000.0,"Comments":"test 2"}
]
Javascript for jqGrid:
jQuery(document).ready(function () {
jQuery("#employeeSalarysGrid").jqGrid({
height: 250,
url: 'http://localhost:50570/api/Test/GetEmployeeSalaries',
mtype: "GET",
contentType: "application/json; charset=utf-8",
datatype: "json",
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
root: function (obj) { return obj; },
page: function (obj) { return 1; },
total: function (obj) { return 1; },
records: function (obj) { return obj.length; },
id: "0",
cell: "",
repeatitems: false
},
datatype: "json",
colNames: ['Id', 'Bank Name', 'Employee name', 'Joining date', 'Salary amount', 'Comments'],
colModel: [
{ name: 'Id', align: "center", hidden:true},
{ name: 'BankName', align: "center", editable: true },
{ name: 'EmployeeName', align: "center", editable: true },
{ name: 'JoiningDate', align: "center", editable: true },
{ name: 'SalaryAmount', align: "center", editable: true },
{ name: 'Comments ', align: "center", editable: true }
],
gridview: true,
autoencode: true,
ignorecase: true,
loadonce: true,
sortname: "InstallmentDate",
sortorder: "asc",
viewrecords: true,
rowNum: 10,
rowList: [10, 15, 20],
pager: '#employeeSalarysPager',
caption: "Employee Salary list"
});
$("#employeeSalarysGrid").jqGrid('navGrid', '#employeeSalarysPager',
{
add: true,
edit: true,
del: true
},
editOption,
addOption,
delOption);
var editOption =
{
width: 400, height: 290, left: 20, top: 30,
reloadAfterSubmit: false, jqModal: false, editCaption: "Edit Record",
bSubmit: "Submit", bCancel: "Cancel", closeAfterEdit: true,
mtype: "POST",
url: 'http://localhost:50570/api/Test/'
};
var addOption = {
width: 400, height: 290, left: 20, top: 30,
reloadAfterSubmit: false, jqModal: false, addCaption: "Add Record",
bSubmit: "Submit", bCancel: "Cancel",
closeAfterAdd: true,
mtype: "PUT",
url: 'http://localhost:50570/api/Test/'
};
var delOption = {
caption: "Delete",
msg: "Delete selected record(s)?",
bSubmit: "Delete", bCancel: "Cancel",
mtype: "DELETE",
url: 'http://localhost:50570/api/Test/'
};
});
Server side API signatures:
public HttpResponseMessage Post(int id, DTOTest value)
public HttpResponseMessage Put(DTOTest value)
public HttpResponseMessage Delete(int id)
Please let me know what is wrong with the code. Methods are not getting invoked. Am i missing anything in html code for jqGrid, OR are the signatures on server code needs to be modified?
Looking forward for some pointers.
Many thanks,
Abhilash

`var URL = 'rest/book';`
...
var delOptions = {
onclickSubmit: function(params, postdata) {
params.url = URL + '/' + postdata;
}
};
you mean this?
it might need "editurl" in your grid instead of "url" in the del(add/edit)Option,like this:
...
height: 250,
editurl: 'http://localhost:50570/api/Test/',
url: 'http://localhost:50570/api/Test/GetEmployeeSalaries',
mtype: "GET",
contentType: "application/json; charset=utf-8",
...
Have a try ?

You need to add URL parameter in your editOption, addOption, deleteOption
var editOption = {
width:400,
height:290,
left:20,
top:30,
reloadAfterSubmit:false,
jqModal:false,
editCaption: "Edit Record",
bSubmit: "Submit",
bCancel: "Cancel",
closeAfterEdit:true,
url:'http://localhost:50570/api/Test/EditEmployee'
};
var addOption = {
width:400,
height:290,
left:20,
top:30,
reloadAfterSubmit:false,
jqModal:false,
addCaption: "Add Record",
bSubmit: "Submit",
bCancel: "Cancel",
closeAfterAdd:true,
url:'http://localhost:50570/api/Test/AddEmployee'
};
var delOption = {
caption: "Delete",
msg: "Delete selected record(s)?",
bSubmit: "Delete",
bCancel: "Cancel",
url:'http://localhost:50570/api/Test/DeleteEmployee'
};

Related

Cannot read property 'length' of null in script

I'm trying to call a function from code behind in script. That function i just returning list of employee
i'm just trying not to use grid view.
I just copy the code in at the same project and changes the names of function and the name inside the colModel: []
here's my script:
function loadMoretha60grid() {
$('#timesheetgrid').jqGrid("GridUnload");
getmoreThan60(function (data) { loadTimesheetTableMoeretha60(data); });
}
function loadTimesheetTableMoeretha60(timelog) {
var lastsel;
var startpage = 1;
$('#timesheetgrid').jqGrid({
datatype: 'local',
data: timelog,
editurl: 'clientArray',
colNames: ['CompanyID', 'EMPName', 'START_DATE', 'END_DATE',
'TOTALHOURS'],
colModel: [
{ name: 'CompanyID', index: 'CompanyID', editable: 'false', align: 'center', width: '150', sortable: false, },
{ name: 'EMPName', index: 'EMPName', editable: 'false', align: 'center', width: '275', resizable: false },
{ name: 'START_DATE', index: 'START_DATE', editable: 'false', align: 'center', width: '175', resizable: false },
{ name: 'END_DATE', index: 'END_DATE', editable: 'false', align: 'center', width: '175', resizable: false },
{ name: 'TOTALHOURS', index: 'TOTALHOURS', editable: 'false', align: 'center', width: '175', resizable: false },
],
pager: '#timesheetgridpager',
viewrecords: true,
forceFit: false,
shrinkToFit: false,
width: '1000',
emptyrecords: "No Record/s found",
loadtext: "Loading",
rowList: [5, 10, 20, 50],
height: 'auto',
caption: 'Timesheet Listing'
});
$('#timesheetgrid').jqGrid('navGrid', '#timesheetgridpager', {
edit: false,
save: false,
add: false,
cancel: false,
del: false,
search: false,
refresh: false
});
$('#timesheetgrid').jqGrid('inlineNav', '#timesheetgridpager', {
add: false,
edit: false,
save: false,
cancel: false,
restoreAfterSelect: false
});
}
function getmoreThan60(callback) {
var timelog = [],
params = {
name: $('#empnamebox').val(),
dateStart: '2019-09-01',
dateEnd: '2019-09-29'
};
showLoadingGif();
$.ajax({
async: true,
type: 'POST',
contentType: 'application/json',
url: baseUrl + 'Timesheet.aspx/getMore60hrs',
data: JSON.stringify(params),
dataType: 'json',
success: function (data) {
timelog = data.d;
hideLoadingGif();
if (typeof callback != 'undefined')
callback(timelog);
},
error: function (xhr, status, error) {
console.log(xhr, status, error);
hideLoadingGif();
}
});
}
here's my method
[WebMethod]
public static void getMore60hrs(string name,string dateStart,string dateEnd) {
TDKDataAccessLayer dataAcc = new TDKDataAccessLayer();
List<morethan> records = new List<morethan>();
dataAcc.DepartID = Convert.ToInt32(DeptID);
dataAcc.Name = name;
dataAcc.DateStart = dateStart;
dataAcc.DateEnd = dateEnd;
records = dataAcc.MoreThan60hrs();
}
By the way
I don't know what to do about this because i came from windows form c#

Unable to bind the data to dropdown in jqgrid when it is editing getting data using web api

$j(document).ready(function () {
$j.ajax({
type: "GET",
url: "http://localhost:9611/api/Master/GetBackendUsersList",
contentType: "json",
dataType: "json",
success: function (data) {
var dataList;
var StatusList = '';
$j('#list2').jqGrid({
caption: "Users Details",
data: data,
datatype: "local",
height: '100%',
width: '100%',
colNames: ["UserName", "RoleId", "Name", "RoleName", "LoginId"],
colModel: [
{ name: "UserName", index: 'UserName', editable: true },
{ name: 'RoleId', index: "RoleId", hidden: true, width: 150, editable: true },
{ name: "Name", index: "Name", editable: true },
{
name: "RoleName", index: "RoleName", editable: true, edittype: 'select', editoptions: {
dataInit: function (element)
{
$j.ajax({
type: "GET",
url: "http://localhost:9611/api/Master/GetRoles",
contentType: "json",
dataType: "json",
success: function (mydata) {
dataList = mydata;
for (var i = 0; i < dataList.length; i++) {
//if (StatusList == "")
// StatusList = dataList[i].RoleId + ":" + dataList[i].RoleName;
//else
StatusList = StatusList + dataList[i].RoleId + ":" + dataList[i].RoleName+ ';' ;
}
}
});
},
value: "0:Select;" + StatusList,
}
},
{ name: 'LoginId', index: "LoginId", hidden: true, width: 150 }
],
gridview: true,
rowNum: 5,
rowList: [5, 10, 15],
pager: '#jQGridDemoPager',
sortname: "UserName",
viewrecords: true,
sortorder: "desc",
//width: '100%',
//height: '100%',
shrinkToFit: false,
editurl: SiteUrl + "api/Master/UpdateBackendUserDetails/" ,
});
$j.extend(true, $j.jgrid.edit, {
recreateForm: true,
beforeShowForm: function ($jform) {
$jform.closest(".ui-jqdialog").position({
of: window, // or any other element
my: "center center",
at: "center center"
});
}
});
$j('#list2').jqGrid('navGrid', '#jQGridDemoPager',
{
add: false,
search: false,
recreateForm: true,
beforeShowForm: function ($jform) {
$jform.find(".FormElement[readonly]")
.prop("disabled", true)
.addClass("ui-state-disabled")
.closest("LoginId")
.prev(".CaptionTD")
.prop("disabled", true)
.addClass("ui-state-disabled");
},
},
{ recreateForm: true }
);
}
});
});
Dropdown data from api is like:
[{"RoleId":1,"RoleName":"Administrator"},{"RoleId":2,"RoleName":"Sales"},{"RoleId":3,"RoleName":"Secretory/President"},{"RoleId":4,"RoleName":"Apartment Owner"},{"RoleId":5,"RoleName":"Apartment User"}]
Use this way :
editoptions:{value: getData()}
and then create one method
function getData(){
var states = [{"RoleId":1,"RoleName":"Administrator"},{"RoleId":2,"RoleName":"Sales"},{"RoleId":3,"RoleName":"Secretory/President"},{"RoleId":4,"RoleName":"Apartment Owner"},{"RoleId":5,"RoleName":"Apartment User"}];
return states;
}
In your case you need to add ajax call in getData() and return values/array which has been created by the result.

Change Value of kendo grid based on second datasource

I am very new to both kendo and javascript so excuse any lapses in knowledge. I have a kendo grid with a field called TicketStatusID. I have another independent datasource with TicketStatusID and TicketStatusName. Is there a way to replace TicketStatusID in my grid with TicketStatusName from my other datasource?
here is my grid:
var commentsDatasource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
//url: sBaseUrl,
url: baseUrl + "TicketIssueComment",
type: "get",
dataType: "json",
contentType: "application/json"
},
create: {
url: baseUrl + "TicketIssueComment",
type: "post",
dataType: "json",
ContentType: 'application/json',
success: refresh
},
},
schema: {
data: "value",
total: function (data) {
return data['odata.count'];
},
model: {
id: "TicketCommentID",
fields: {
TicketCommentID: { type: "number" },
TicketID: { type: "number" },
TicketCommentValue: { type: "string" },
TicketCommentCreatedBy: { type: "string", defaultValue: "z13tas", editable: false },
TicketCommentCreatedTS: { type: "date", editable: false },
TicketStatusID: { type: "number", editable: false },
//TicketStatusName: { type: "string", editable: false }
}
}
},
filter: { field: "TicketID", operator: "eq", value: filterValue },
pageSize: 50,
serverPaging: true,
serverFilering: true,
serverSorting: true,
sort: { field: "TicketID", dir: "asc" },
});
//-----------------KENDO GRID-----------------
$("#gridComments").kendoGrid({
dataSource: commentsDatasource,
pageable:
{
refresh: true,
pageSizes: [10, 25, 50, 100],
buttonCount: 5
},
//height: 300,
width: 300,
//sortable: true,
toolbar: ["create", "save", "cancel"],
scrollable: true,
reorderable: true,
editable: true,
selectable: "row",
resizable: true,
edit: function edit(e) {
if (e.model.isNew() == false) {
$('input[name=TicketCommentValue]').parent().html(e.model.TicketCommentValue);
}
},
columns: [
{ field: "TicketCommentValue", title: "Comment", width: "500px" },
{ field: "TicketStatusID", title: "Status", width: "100px" },
{ field: "TicketCommentCreatedBy", title: "Created By", width: "100px" },
{ field: "TicketCommentCreatedTS", title: "Created Date", width: "150px", format: "{0:MM-dd-yyyy hh:mm tt}" }
]
});
and here is my second datasource:
var StatusDatasource = new kendo.data.DataSource({
type: "odata",
transport: {
read: {
dataType: "json",
url: baseUrl + "TicketIssueStatusView",
}
},
schema: {
data: "value",
total: function (data) {
return data['odata.count'];
},
model: {
id: "TicketStatusID",
fields: {
TicketStatusID: { type: "number" },
TicketStatusName: { type: "string" },
TicketStatusDescription: { type: "string" },
TicketStatusUpdatedTS: { type: "date" },
TicketStatusUpdatedBy: { type: "string" },
}
}
},
serverFilering: true,
optionLabel: "--Select Value--"
});
I think I may be onto something with this solution here - http://demos.telerik.com/kendo-ui/grid/editing-custom - but Telerik's documentation offers no explanation of how to implement. Thanks
Do it from this example.
Add this field where you want to change kendo grid.
$.ajax({
cache: false,
type: "POST",
url: "#Html.Raw(Url.Action("assing", "Customer"))",
data: postData,
complete: function (data) {
//reload antoher grid
var grid = $('#Customer-grid').data('kendoGrid');
grid.dataSource.read();
},
error: function (xhr, ajaxOptions, thrownError) {
alert(thrownError);
},
traditional: true
});
from below code your problem is solve..try it first.
var grid = $('#Customer-grid').data('kendoGrid');
grid.dataSource.read();
{
field: "TicketStatusID",
title: "Status",
width: "100px",
template: #= StatusDatasource.get(data.TicketStatusID).TicketStatusName #
}
Remember your StatusDatasource should be top level, I mean available as windows.StatusDatasource, and both initialized and read data before grid initialization (without first condition there will be an error, and without second you will see undefined inside a column).

How to get the particular cell value in JQgrid

I have written a JQGrid which was working fine but I need to fill the sub grid based on the selected row of main grid. How can I get the selected row cell value to pass in the url of subgrid.
columns in the main grid ---- Id,Firstname,Lastname,Gender.
I need to get selected row of "Id" value.
Here is my script
$(document).ready(function () {
jQuery("#EmpTable").jqGrid({
datatype: 'json',
url: "Default1.aspx?x=getGridData",
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: { repeatitems: false, root: "rows", page: "page", total: "total", records: "records" },
colNames: ['PID', 'First Name', 'Last Name', 'Gender'],
colModel: [
{ name: 'PID', width: 60, align: "center", hidden: true, searchtype: "integer", editable: true },
{ name: 'FirstName', width: 180, sortable: true, hidden: false, editable: true, sorttype: 'string', searchoptions: { sopt: ['eq', 'bw']} },
{ name: 'LastName', width: 180, sortable: false, hidden: false, editable: true },
{ name: 'Gender', width: 180, sortable: false, hidden: false, editable: true, cellEdit: true, edittype: "select", formater: 'select', editrules: { required: true, edithidden: true }, editoptions: { value: getAllSelectOptions()}}],
loadonce: true,
pager: jQuery('#EmpPager'),
rowNum: 5,
rowList: [5, 10, 20, 50],
viewrecords: true,
sortname: 'PID',
sortorder: "asc",
height: "100%",
editurl: 'Default1.aspx?x=EditRow',
subGrid: true,
// subGridUrl: 'Default1.aspx?x=bindsubgrid',
subGridRowExpanded: function (subgrid_id, row_id) {
// var celValue = jQuery('#EmpTable').jqGrid('getCell', rowId, 'PID');
var subgrid_table_id, pager_id;
subgrid_table_id = subgrid_id + "_t";
pager_id = "p_" + subgrid_table_id;
$("#" + subgrid_id).html("");
jQuery("#" + subgrid_table_id).jqGrid({
url: "Default1.aspx?x=bindsubgrid&PID=" + row_id + "",
datatype: "json",
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: { repeatitems: false, root: "rows", page: "page", total: "total", records: "records" },
colNames: ['PID', 'First Name', 'Last Name', 'Gender'],
colModel: [
{ name: 'PID', width: 60, align: "center", hidden: true, searchtype: "integer", editable: true },
{ name: 'FirstName', width: 180, sortable: true, hidden: false, editable: true, sorttype: 'string', searchoptions: { sopt: ['eq', 'bw']} },
{ name: 'LastName', width: 180, sortable: false, hidden: false, editable: true },
{ name: 'Gender', width: 180, sortable: false, hidden: false, editable: true, cellEdit: true, edittype: "select", formater: 'select', editrules: { required: true, edithidden: true }, editoptions: { value: getAllSelectOptions()}}],
loadonce: true,
rowNum: 5,
rowList: [5, 10, 20, 50],
pager: pager_id,
sortname: 'PID',
sortorder: "asc",
height: '100%'
});
jQuery("#" + subgrid_table_id).jqGrid('navGrid', "#" + pager_id, { edit: false, add: false, del: false })
}
})
Please help to find the cell value.
Thanks
purna
If 'PID' column contains unique value which can be used as the rowid then you should add key: true in the definition of the 'PID' column in colModel. jqGrid will assign id attribute of <tr> elements (the rows of the grid) to the value from 'PID' column. After that row_id parameter of subGridRowExpanded will contain the value which you need and you will don't need to make any additional getCell call.
Additional remark: I strictly recommend you to use idPrefix parameter for subgrids and probably for the grids. In the case jqGrid will use the value of id attribute which have the specified prefix. If will allow to solve conflicts (id duplicates in HTML page). Currently you can have the same rowids for the rows of subgrids and to the rows of the main grid. See here more my old answers on the subject.

Jqgrid custom formatter button click not working

I created a grid and one of my column has a custom button in each row. When I click the button my click event is not invoked.
My jqgrid:
$('#QuoteLineTable').jqGrid({
url: $('#url').val(),
datatype: 'json',
type: 'POST',
postData: { Id: $("#Id").val() },
colNames: ['Id', 'Quote Number', 'Valid Until Date','View Line Item'],
colModel: [
{ name: "QuoteLineId", index: "QuoteLineId", hidden: false, hidedlg: true },
{ name: 'QuoteNumber', index: "QuoteNumber" },
{ name: 'ValidUntil', formatter: "date", formatoptions: { newformat: "d/m/Y" }, width: '100px' },
{ name: 'View Line Item', formatter: viewLineBtn }
],
multiselect: true,
emptyrecords: "No Quote Line to view",
gridview: true,
autoencode: true,
loadtext: "Loading...",
loadonce: true,
rowNum: 3,
rowList: [10, 20, 30],
pager: '#LinePager',
height: '100%',
caption: "Quote List",
autowidth: true,
sortname: 'QuoteNumber',
ajaxGridOptions: { type: 'POST', contentType: "application/json; charset=utf-8" },
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "totalPages",
records: "totalRecords",
id: "QuoteLineId"
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
onCellSelect: function(rowid,e) {
alert("rowid=" + rowid );
},
ondblClickRow: function(rowid) {
var $model = $('#LineItemMyModal');
$.ajax({
type: "GET",
url: $('#urlItemDetails').val(),
data: { LineId: rowid },
success: function(r) {
$model.html(r);
$model.modal('show');
}
});
}
}).navGrid('#QuoteLinePager', { edit: false, add: false, del: false, search: true });
function viewLineBtn(cellvalue, options, rowObject) {
return "<button class=\"viewLineItem\">View Line Item</button>"
};
$('.viewLineItem').click(function (rowId) {
alert("hi");
alert(rowId);
});
Basically I am not sure how to call the click event for button class= viewLineItem.
I tried to use onCellSelect or beforeSelectRow event but I also need to use ondblClickRow to populate a modal. So I am looking for other options without using oncellSelect.
Try something like this.
$('#QuoteLineTable').jqGrid({
url: $('#url').val(),
datatype: 'json',
type: 'POST',
postData: { Id: $("#Id").val() },
colNames: ['Id', 'Quote Number', 'Valid Until Date','View Line Item'],
colModel: [
{ name: "QuoteLineId", index: "QuoteLineId", hidden: false, hidedlg: true },
{ name: 'QuoteNumber', index: "QuoteNumber" },
{ name: 'ValidUntil', formatter: "date", formatoptions: { newformat: "d/m/Y" }, width: '100px' },
{ name: 'View Line Item', formatter: viewLineBtn }
],
multiselect: true,
emptyrecords: "No Quote Line to view",
gridview: true,
autoencode: true,
loadtext: "Loading...",
loadonce: true,
rowNum: 3,
rowList: [10, 20, 30],
pager: '#LinePager',
height: '100%',
caption: "Quote List",
autowidth: true,
sortname: 'QuoteNumber',
ajaxGridOptions: { type: 'POST', contentType: "application/json; charset=utf-8" },
jsonReader: {
repeatitems: false,
root: "rows",
page: "page",
total: "totalPages",
records: "totalRecords",
id: "QuoteLineId"
},
serializeGridData: function(postData) {
return JSON.stringify(postData);
},
onCellSelect: function(rowid,e) {
alert("rowid=" + rowid );
},
ondblClickRow: function(rowid) {
var $model = $('#LineItemMyModal');
$.ajax({
type: "GET",
url: $('#urlItemDetails').val(),
data: { LineId: rowid },
success: function(r) {
$model.html(r);
$model.modal('show');
}
});
}
}).navGrid('#QuoteLinePager', { edit: false, add: false, del: false, search: true });
function viewLineBtn(cellvalue, options, rowObject) {
var rowid= options.rowid;
var button = "<button class=\"viewLineItem\" id="+ rowid+">View Line Item</button>"
$('#' + rowid).die();
$('#' + rowid).live('click', function (rowId) {
alert("hi");
alert(rowId);
});
};
It works for me:
$('#QuoteLineTable').jqGrid({
....
colModel: [
...
{ name: 'View Line Item', formatter: viewLineBtn }
]
loadComplete: function (data) {
console.log(data); // You can view the object
let rowDataArray = data.rows;
for (let i = 0, j = rowDataArray.length; i < j; i++)
{
let temp = rowDataArray[i];
$("#btn_" + temp.id).click(() => {
m_alert(temp.content);
});
}
}
});
function viewLineBtn(cellvalue, options, rowObject)
{
return "<button id='btn_" + rowObject.id + "'>View Line Item</button>"
}

Categories

Resources