I'm new to WebApi and I have problem with the received post parameters.
I want to populate jqgrid with data received from webapi controller method.
The grid code is as follows:
buildPostData: function (postData) {
var parameters = {
page: postData.page,
rows: postData.rows,
sidx: '',
sord: '',
_search: false,
searchField: '',
searchString: '',
searchOper: '',
filter: { groupOp: '', rules: [] }
};
$.extend(parameters, postData);
var data = {
parameters: parameters
};
return JSON.stringify(data);
}
bindGridAllData: function () {
var viewModel = this;
jQuery("#AllDataGrid").jqGrid({
url: 'api/DataApi/GetAllData',
datatype: 'json',
mtype: 'POST',
ajaxGridOptions: {
contentType: 'application/json; charset=utf-8'
},
serializeGridData: viewModel.buildPostData,
serializeRowData: function (data) {
return JSON.stringify(data);
},
jsonReader: { repeatitems: false, root: "d.rows", page: "d.page", total: "d.total", records: "d.records" },
colNames: ['DataId', 'Title', 'Description', 'Date', 'UserId', 'Name', 'Surname', 'PicturePath', 'NumberOfComments', ''],
colModel: [
{ name: 'DataId', index: 'DataId', width: 10, hidden: true, editable: false, sortable: false, key: true },
{ name: 'Title', index: 'Title', width: 10, editable: false, align: 'left', sortable: true, hidden: true },
{ name: 'Description', index: 'Description', width: 10, editable: false, align: 'left', sortable: true, hidden: true },
{ name: 'Date', index: 'Date', width: 10, editable: false, align: 'left', sortable: true, hidden: true },
{ name: 'UserId', index: 'UserId', width: 10, editable: false, align: 'left', sortable: true, hidden: true },
{ name: 'Name', index: 'Name', width: 10, editable: false, align: 'left', sortable: true, hidden: true },
{ name: 'Surname', index: 'Surname', width: 10, editable: false, align: 'left', sortable: true, hidden: true },
{ name: 'PicturePath', index: 'PicturePath', width: 10, editable: false, align: 'left', sortable: true, hidden: true },
{ name: 'NumberOfComments', index: 'NumberOfComments', width: 10, editable: false, align: 'left', sortable: true, hidden: true },
{
name: 'DataInformation', index: 'DataInformation', width: 200, editable: false, align: 'left', sortable: true, formatter: function (cellvalue, options, rowObject) {
var template = $('<div data-bind="template: { name: \'DataRecord\', data: DataRecord, ajax: { async: false } }"></div>');
var data = { DataRecord: rowObject };
ko.applyBindings(data, template[0]);
return template.html();
}
}
],
height: '100%',
width: 900,
pager: '#resultGridAllDataPager',
rowNum: 10,
rownumbers: false,
scroll: false,
sortname: 'Date',
sortorder: "asc",
gridview: true,
hoverrows: false,
viewrecords: true,
cmTemplate: { title: false },
loadComplete: function () {
}
});
}
And the WebApi method is:
[HttpPost]
public JQGridData GetAllData(JQGridSearchParameters parameters)
{
using (dataMKbazaEntities context = new dataMKbazaEntities())
{
JQGridData grid = new JQGridData();
var allData = context.ispolniSITEpodatoci().ToList();
List<object> data = new List<object>();
foreach (var ad in allData)
{
data.Add(new {
DataId=ad.podatokID,
Title=ad.naslov,
Description=ad.opis,
Date=ad.datum,
UserId=ad.idKORISNIK,
Name=ad.ime,
Surname=ad.prezime,
PicturePath=ad.slika,
NumberOfComments=ad.brojKOMENTARI
});
}
grid.rows = data;
grid.page = parameters.page;
grid.records = data.Count;
grid.total = (int)Math.Ceiling((float)data.Count / (float)parameters.rows);
return grid;
}
}
When sending data, parameters have values defined from buildPostData method but when received in WepApi controller method they are null.
I have tried with [FromBody] in webapi method but with no success.
Status code in http request is 200 OK
Make sure of the following:
Your raw request has the Content-Type header. Looking at your client code you seem to be sending it, but just wanted to make sure that it is indeed sent over the wire. Web API had a bug where if you do not send Content-Type header, since we do not know which formatter to deserialize the content, we default to the default value of the C# type. In this case it could be 'null'. This has been fixed later and is not yet publicly available though.
Have the following check to see any model state errors:
if (!ModelState.IsValid)
{
throw new HttpResponseException(Request.CreateErrorResponse(HttpStatusCode.BadRequest, this.ModelState));
}
Related
$(document).ready(function () {
BindGrid('', '', '', '', 1, 2, '', '', sessionStorage.UserID);
});
function Search() {
$('#modal_Advance_Search').modal('hide');
var channelselected = $('#dd_channel option:selected');
var channelarray = [];
$(channelselected).each(function (index, channelsel) {
channelarray.push([$(this).val()]);
});
var Channel = channelarray.toString();
var Distselected = $('#dd_dist_category option:selected');
var Distarray = [];
$(Distselected).each(function (index, channelsel) {
Distarray.push([$(this).val()]);
});
var DistributorCategory = Distarray.toString();
var ARNNo = "";
var token = $("#txt_arn").tokenInput("get");
var names = [];
$.each(token, function (i, obj) {
names.push(obj.name);//build an array of just the names
});
ARNNo = names.toString();
sessionStorage.setItem("DistributorCategoryMaster", DistributorCategory);
sessionStorage.setItem("ChannelCreateMaster", Channel);
sessionStorage.setItem("ARNCreateMaster", ARNNo);
sessionStorage.setItem("ismasterqueue", true);
$("#hdr_name").text("Master Q");
$("#spn_user_name").text(sessionStorage.UserName);
$("#spn_role_name").text(sessionStorage.RoleName);
BindGrid(ARNNo, Channel, '', DistributorCategory, 1, 2, Utility.ListSearchText, '', sessionStorage.UserID)
}
function BindGrid(ArnNo1, Channel1, ARNName1, DistributorCategory1, Status1, MasterQueueStatus1, SearchFilter1, MemoLevel1, UserID1) {
$("#tbl_masterqueue").jqGrid({
url: "/Pages/MSQ.aspx/GetCreateBaseRackRate",
mtype: 'POST',
postData:
{
ArnNo: ArnNo1, Channel: Channel1, ARNName: ARNName1, DistributorCategory: DistributorCategory1, Status: Status1, MasterQueueStatus: MasterQueueStatus1, SearchFilter: SearchFilter1, MemoLevel: MemoLevel1, UserID: UserID1
},
datatype: "json",
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
jsonReader: {
repeatitems: false,
root: function (obj) { return obj.d; }
},
colNames: ['Select', 'Memoid', 'Memo Number', 'Memo Type', 'Memo Type ID', 'Category', 'ARN No', 'ARN Name', 'Date From', 'Date To', 'Status', 'Status', 'Raised By', 'Raised On', 'Time', 'Ageing', 'Last Action By', 'Pending With'],
colModel: [
{ name: 'edi', index: 'edi', formatter: MasterQueue.ReturnRadioBox, width: '60px;', disabled: true, hidden: true, sortable: false },
{ name: 'PaymentMemoId', index: 'PaymentMemoId', width: 120, hidden: true, sortable: false },
{ name: 'MemoNumber', index: 'MemoNumber', align: 'center', formatter: MasterQueue.ReturnSearchHyperLink, sortable: false },
{ name: 'MemoTypeName', index: 'MemoTypeName', width: 120, sortable: false },
{ name: 'MemoTypeID', index: 'MemoTypeID', hidden: true, sortable: false },
{ name: 'DistributorCategoryName', index: 'DistributorCategoryName', width: 260, sortable: false },
{ name: 'ARNNo', index: 'ARNNo', width: 90, sortable: false },
{ name: 'ARNName', index: 'ARNName', width: 260, sortable: false },
{ name: 'DateFrom', index: 'DateFrom', sorttype: "date", align: 'center', width: 90, sortable: false },
{ name: 'DateTo', index: 'DateTo', align: 'center', width: 90, sortable: false },
{ name: 'MemoStatus', index: 'MemoStatus', align: 'center', width: 90, hidden: true, sortable: false },
{ name: 'MemoStatusDisplay', index: 'MemoStatusDisplay', align: 'center', width: 90, sortable: false },
{ name: 'CreatedByName', index: 'CreatedByName', align: 'left', sortable: false },
{ name: 'RaisedOnDate', index: 'RaisedOnDate', width: 90, align: 'center', sortable: false },
{ name: 'RaisedOnTime', index: 'RaisedOnTime', width: 50, align: 'center', sortable: false },
{ name: 'Ageing', index: 'Ageing', width: 70, align: 'right', sortable: false },
{ name: 'ModifiedByName', index: 'ModifiedByName', align: 'left', sortable: false },
{ name: 'PendingWith', index: 'PendingWith', align: 'left', sortable: false },
],
rowNum: 100,
rowList: [100, 200, 300, 400, 500],
pager: '#pager',
sortname: 'PaymentMemoId',
viewrecords: true,
sortorder: "desc",
gridview: true,
height: '510px',
loadonce: true,
gridview: true
});
jQuery("#tbl_masterqueue").jqGrid('navGrid', '#pager', { add: false, edit: false, del: false, search: true, refresh: true },
{}, {}, {}, { multipleSearch: true, multipleGroup: true, showQuery: true });
}
I have created one method to bind grid during pageload,its working fine but again when am calling the same method during filtering/searching on button click this method is not working.I am using JQGrid,please help to fix.
I am using jqGrid V 4.6.0. and trying to implement grid with inline edit/delete functionality.I used formatter:'actions' for acheive this and also getting edit/delete icons in each row.But when i click on those icons i am getting following error in console :Uncaught TypeError: Cannot read property 'rowactions' of undefined and nothing happens in grid.same code and same example i've implemented before with jqGrid V4.4.4 and it worked well ,but in V4.6.0 i got this error.Please somebody help me.Thanks in advance :)
Code for reference:
jQuery("#theGrid").jqGrid({
url: '/Student/Grid',
datatype: "json",
colNames: ['Id', 'Firstname', 'Middlename', 'Lastname', 'Birthdate', 'Birthplace', 'State', 'Nationality', 'Religion', 'Ishandicaped ?', 'Actions'],
colModel: [
{ key: true, name: 'Id', sortable: true, resize: true, align: "center" },
{ key: false, name: 'FirstName', index: 'FirstName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'MiddleName', index: 'MiddleName', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'LastName', index: 'LastName', editable: true, align: "center", editrules: { required: true } },
{
key: false, name: 'Birthdate', index: 'Birthdate', editable: true, align: "center", editrules: { required: true }, formatter: 'date', editoptions: {
dataInit: function (el) {
setTimeout(function () {
$(el).datepicker({
dateFormat: "dd-M-yy",
autoSize: true,
changeYear: true,
changeMonth: true,
showButtonPanel: true,
showWeek: true
});
}, 200);
}
}
},
{ key: false, name: 'Birthplace', index: 'Birthplace', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'State', index: 'State', editable: true, align: "center", edittype: "select", editoptions: { value: "GJ:Gujarat;MH:Maharashtra;DL:Delhi;BNG:Banglore;RJ:Rajasthan" }, editrules: { required: true } },
{ key: false, name: 'Nationality', index: 'Nationality', editable: true, align: "center", editrules: { required: true } },
{ key: false, name: 'Religion', index: 'Religion', editable: true, align: "center", editrules: { required: true } },
{
key: false, name: 'IsHandicaped', index: 'IsHandicaped', editable: true, align: "center", edittype: "checkbox", editoptions: { value: "True:False" }, formatter: Demo1
},
{
key: false,
name: 'Actions',
index: 'tax',
width: 80,
align: "center",
formatter: 'actions',
formatoptions: {
delOptions: { url: '/Student/Delete' }
}
}
],
rowNum: 10,
rownumbers: true,
autowidth: true,
rowList: [5, 10, 20],
pager: '#gridPager',
viewrecords: true,
sortorder: "desc",
reloadAfterSubmit: true,
altclass: 'table table-bordered table-striped',
jsonReader: {
repeatitems: false
},
caption:'Studentdata JqGrid V4.4.4',
editurl: '/Student/Edit',
mtype: "post",
height: '100%',
hiddengrid: false,
serializeRowData: function (postData) {
debugger;
// new row id is "new_row"
postData.Id == "jqg1" ? postData.oper = "add" : postData.oper = "add";
return postData;
},
afterSubmit: function (response, postdata) {
if (response.responseText == "") {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [true, ''];
} else {
$(this).jqGrid('setGridParam',
{ datatype: 'json' }).trigger('reloadGrid'); //Reloads the grid after Add
return [false, response.responseText];
}
}
}
});
I have a customer details where I am showing the customers bill status which is working fine,
Is it possible to rebind the grid once we loaded the data in grid for example:
when I am coming from another page how to apply search on the existing grid data and rebind it to grid.
Below is my colmodel and other properties which I am using but not working properly,
$("#BillDetails").jqGrid({
url: '../Handler.ashx,
datatype: "json",
colNames: [ 'S.No', 'Bill NO', 'Customer Name', 'Customer Type', 'Bill Date',Bill Status'],
colModel: [
{ name: 'SERIAL', sortable: false, search: true, stype: 'text', width: 40, hidden: false,
align: 'right', sorttype: 'int' },
{ name: 'BILL_NO', sortable: false, search: true, width: 80, hidden: false,
align: 'right',formatter: editLink,},
{ name: 'CUSTOMER_NAME', search: true, align: 'left', width: 150, aligh: 'left',
sortable: false },
{ name: 'CHECK_TYPE', align: 'left', width: 150, search: true, aligh: 'left',
sortable: false},
{ name: 'BILL_DATE', width: 85, sortable: false, search: true, align: 'center',
sorttype: 'date', formatter: "date", formatoptions: { newformat: 'd/m/Y' } },
{ name: 'BILL_STATUS', width: 90, align: 'left', search: true, stype: 'select',
searchoptions: { value: 'Pending:Pending;
On Hold:On Hold;Clear:Clear;Incompelete:InComplete,sortable: false } },
],
width: '980',
height: '450',
shrinkToFit: false,
sortable: true,
mtype: 'GET',
scrollbar: true,
sortname: 'BILL_NO',
sortorder: 'asc',
hidegrid: false,
loadonce: true,
ignoreCase: true,
rowNum: 50,
pager: '#Pager',
viewrecords: true,
// Search on page load from grid data
gridComplete: function () {
var searchFilter = "Clear"; // In this I will receive the the status from query string,
//for now i have provided the the hard core value to test
var gridData = $("#jQGridDemo").jqGrid('getGridParam', 'data');
console.log(gridData);
if (searchFilter != "") {
var grid = $("#BillDetails"), f;
f = { rules: [] };
f.rules.push({ field: "STATUS", op: "eq", data: searchFilter });
grid[0].p.search = true;
$("#BillDetails").setGridParam({ data: gridData, postData: { filters: f },
datatype: "local", });
}
}
});
If you want to reload jqGrid when coming from another page with search parameters you could use postData property of jqGrid.
Something like this:
$("#BillDetails").jqGrid({
url: '../Handler.ashx',
datatype: "json",
mtype: 'GET',
postData:
{
Page: 'Dashboard',
strUserID: strUserID,
}
You can populate this property with js or on server side as you need.
UPDATE
You also can use setGridParam method of jqgrid:
$("#BillDetails").jqGrid('setGridParam',
{
postData: {
Page: 'Dashboard',
strUserID: strUserID,
}
});
$("#BillDetails").trigger("reloadGrid");
But as i understand this way you also just add values to postData property.
Also you can try it this way:
$("#BillDetails").trigger('reloadGrid', [{page:1}]);
You can pass there your new params as on grid init.
i am using jqgrid and facing a problem with column width
here is my js code
jQuery(document).ready(function () {
var grid = jQuery("#grid");
grid.jqGrid({
url: '/Admin/GetUserForJQGrid',
datatype: 'json',
mtype: 'Post',
cellsubmit: 'remote',
cellurl: '/Admin/GridSave',
//formatCell: emptyText,
colNames: ['Id', 'Privileges', 'First Name', 'Last Name', 'User Name', 'Password', 'Password Expiry', 'Type', 'Last Modified', 'Last Modified By', 'Created By', ''],
colModel: [
{ name: 'Id', index: 'Id', key: true, hidden: true, editrules: { edithidden: true } },
{ name: 'Privileges', index: 'Privileges', width: "350", resizable: false, editable: false, align: 'center', formatter: formatLink, classes: 'not-editable-cell' },
{ name: 'FirstName', index: 'FirstName', width:350, align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'LastName', index: 'LastName',width:350, align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'UserName', index: 'UserName', width:300,align: "left", sorttype: 'text', resizable: true, editable: true, editrules: { required: true } },
{ name: 'Password', index: 'Password',width:400, align: "left", sorttype: 'text', resizable: true, editable: false, editrules: { required: true }, classes: 'not-editable-cell' },
{
name: 'Password_Expiry',width:250, index: 'Password_Expiry', align: "left", resizable: true, editable: true, editoptions: {
size: 20, dataInit: function (el) {
jQuery(el).datepicker({
dateFormat: 'yy-mm-dd', onSelect: function (dateText, inst) {
jQuery('input.hasDatepicker').removeClass("hasDatepicker")
return true;
}
});
}
}
},
{
name: 'Type', width: "250", index: 'Type', sorttype: 'text', align: "left", resizable: true, editable: true, editrules: { required: true }, edittype: 'select', editoptions: {
value: {
'Normal': 'Normal',
'Sales': 'Sales',
'Admin': 'Admin',
'SuperAdmin': 'SuperAdmin'
},
dataEvents: [
{
type: 'change',
fn: function (e) {
var row = jQuery(e.target).closest('tr.jqgrow');
var rowId = row.attr('id');
jQuery("#grid").saveRow(rowId, false, 'clientArray');
}
}
]
}
},
{ name: 'Modified',width:250, index: 'Modified', sorttype: 'date', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'ModifiedBy', width:250, index: 'ModifiedBy', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'CreatedBy', width:250,index: 'CreatedBy', sorttype: 'text', align: "left", resizable: true, editable: false, classes: 'not-editable-cell' },
{ name: 'Delete',width:50, index: 'Delete', width: 25, resizable: false, align: 'center', classes: 'not-editable-cell' }
],
rowNum: 10,
rowList: [10, 20, 50, 100],
sortable: true,
delete: true,
pager: '#pager',
height: '100%',
width: "650",
afterSubmitCell: function (serverStatus, rowid, cellname, value, iRow, iCol) {
var response = serverStatus.responseText;
var rst = 'false';
debugger;
if (response == rst) {
debugger;
setTimeout(function () {
$("#info_dialog").css({
left: "644px", // new left position of ERROR dialog
top: "380px" // new top position of ERROR dialog
});
}, 50);
return [false, "User Name Already Exist"];
}
else {
return [true, ""];
}
},
//rowNum: 10,
//rowList: [10, 20, 50, 100],
sortable: true,
loadonce: false,
ignoreCase: true,
caption: 'Administration',
search: false,
del: true,
cellEdit: true,
hidegrid: false,
pgbuttons : false,
pginput : false,
//viewrecords: true,
gridComplete: function () {
var ids = grid.jqGrid('getDataIDs');
for (var i = 0; i < ids.length; i++) {
var isDeleted = grid.jqGrid('getCell', ids[i], 'Delete');
if (isDeleted != 'true') {
grid.jqGrid('setCell', ids[i], 'Delete', '<img src="/Images/delete.png" alt="Delete Row" />');
}
else {
grid.jqGrid('setCell', ids[i], 'Delete', ' ');
}
}
}
}
);
grid.jqGrid('navGrid', '#pager',
{ resize: false, add: false, search: false, del: false, refresh: false, edit: false, alerttext: 'Please select one user' }
).jqGrid('navButtonAdd', '#pager',
{ title: "Add New users", buttonicon: "ui-icon ui-icon-plus", onClickButton: showNewUsersModal, position: "First", caption: "" });
});
i need a scrollable grid , when use come to this page i have to show the first 7 columns only just seven in full page. i have 11 columns in my grid rest of the columns can be seen by using scroll, but first 7 should be shown when grid loads. and every column should be re-sizable. can any body help me, i will 100% mark your suggestion if it works for me ...thank you ;) . if something is not explained i am here to explain please help me
and can i save the width of column permanently when user re-size the column, so when next time grid get loads the column should have the same width which is set by the user by re-sizing.. is it possible ?
I am not sure what you want,but you can auto adjust the width with JqGrid autowidth and shrinkToFit options.
Please refer this Post jqGrid and the autowidth option. How does it work?
this will do the trick.
I've following Grid to display data, now when I want to add new record it gives the error 'NO URL IS SET'
$(document).ready(function () {
$('#PRGrid').jqGrid({
//url from wich data should be requested
url: '#Url.Action("BindData")?FillType=' + getFillType(),
//event for inline edit
onSelectRow: function (currentSelectedRow) {
if (currentSelectedRow && currentSelectedRow != $.lastSelectedRow) {
//save changes in row
$('#PRGrid').jqGrid('saveRow', $.lastSelectedRow, false);
$.lastSelectedRow = currentSelectedRow;
}
//trigger inline edit for row
},
//type of data
datatype: 'json',
//url access method type
mtype: 'POST',
//columns names
colNames: ['Code', 'Name', 'No_Rooms', 'Dept_Code', 'Total_Items'],
//columns model
colModel: [
{ name: 'Code', index: 'Code', align: 'left', width: '120px', editable: true, edittype: 'select', editoptions: { maxlength: 25, dataUrl: '#Url.Action("GetRooms")',
dataEvents: [{
type: 'change', fn: function (e) {
var ret = $.ajax({
url: '#Url.Action("selectRoom")?id=' + $(this).val(),
async: false,
success: function (ret) {
$('#Name').val(ret.Name);
$('#No_Rooms').val(ret.qty);
$('#Dept_Code').val(ret.DeptCode);
$('#Total_Items').val(ret.Total_Items);}
});}
}]
}},
{ name: 'Name', index: 'Name', align: 'left', formatter: "text", width: '185px', editable: true, editrules: { required: true }, editoptions: { readonly: 'readonly'} },
{ name: 'No_Rooms', index: 'No_Rooms', align: 'left', formatter: "text", width: '102px', integer: true, editable: true, editrules: { required: true }, editoptions: { readonly: 'readonly'} },
{ name: 'Dept_Code', index: 'Dept_Code', align: 'left', formatter: "text", width: '78px', editable: true, editrules: { required: true }, editoptions: { readonly: 'readonly'} },
{ name: 'Total_Items', index: 'Total_Items', align: 'left', formatter: "text", width: '82px', integer: true, editable: true, editrules: { required: true }, editoptions: { readonly: 'readonly'} },
],
//pager for grid
pager: $('#PRGridPager'),
//number of rows per page
rowNum: 5,
//initial sorting column
sortname: 'Code',
//initial sorting direction
sortorder: 'asc',
recreateForm:true,
//we want to display total records count
viewrecords: true,
//grid height
height: '100%'
});
$('#PRGrid').jqGrid('navGrid', '#PRGridPager',
{ add: true, del: true, edit:false, search: true },
{width: '330', url:'#Url.Action("InsertPRGridRecord")', closeAfterAdd: true },
{width: '330', url:'#Url.Action("DeleteGridRecord")'});
var dialogPosition = $(this).offset();
Problem arrise when I want to add or delete the record from the grid,
Here I've defined both the methods InsertPRGridRecord() and DeleteGridRecord(), but it gives the same error 'NO URL IS SET' at the time of submitting the data on Add Record or Delete Record dialog.
I think the problem exist because you use incorrect the parameters of navGrid. Your current code uses '#Url.Action("DeleteGridRecord")' as URL of "Add" and '#Url.Action("InsertPRGridRecord")' as URL of "Edit". The URL of "Delete" is not specified.