I am trying to fill a jqgrid. The grid is rendered but no data is displayed. I know my controller -- as called through a standard ajax function -- is working. It returns the data I'd expect.
How do I verify that jqgrid is returning the same data and what am I doing incorrectly that is not allowing the data to be dispayed?
jqgrid:
<script type="text/javascript">
jQuery(document).ready(function() {
$.ajaxSetup({ cache: false });
var rvtoken = $("input[name='__RequestVerificationToken']").val();
var ModuleId = #Dnn.ModuleContext.ModuleId;
var TabId = #Dnn.ModuleContext.TabId;
$('#grid').jqGrid({
url: '/DesktopModules/MVC/CW.GridTest/Item/getArtists2',
datatype: 'json',
mtype: 'POST',
contentType: 'application/json',
loadBeforeSend: function(jqXHR) {
jqXHR.setRequestHeader('ModuleId', ModuleId);
jqXHR.setRequestHeader( 'TabId', TabId);
jqXHR.setRequestHeader('RequestVerificationToken', rvtoken);
},
colNames: ['ArtistID', 'ArtistName', 'City'],
colModel: [
{ name: 'ArtistID', index: 'ArtistID', width: 80, align: 'left', editable: false },
{ name: 'Name', index: 'ArtistName', width: 120, align: 'left', editable: true },
{ name: 'Location', index: 'City',width: 60,align: 'left',editable: true}
],
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown);
alert('HTTP message body (jqXHR.responseText): ' + '\n' + jqXHR.responseText);
},
loadOnce: true,
autoencode: true,
height: '100%',
rowNum: 10,
emptyrecords: 'No records',
sortname: 'ArtistID',
sortorder: 'desc',
viewrecords: true,
caption: 'Artists',
width: 300,
gridview: true,
jsonReader:
{
total: 'total',
page: 'page',
records: 'records',
root: 'rows',
repeatitems: false,
id: 'ArtistID'
}
});
jQuery("#grid").jqGrid('navGrid', '#pager', { edit: false, add: false, del: false });
});
</script>
<div>
<table id="grid"></table>
<div id="pager"></div>
</div>
Returned data from standard ajax:
{
"total":100,
"page":99,
"records":6,
"rows":"[
{\"ArtistID\":1,\"ArtistName\":\"Clayton Knight\",\"City\":\"Tigard\"},
{\"ArtistID\":2,\"ArtistName\":\"Corral Creek Bluegrass\",\"City\":\"Sherwood\"},
{\"ArtistID\":3,\"ArtistName\":\"Never Strangers Band\",\"City\":\"Portland\"},
{\"ArtistID\":5,\"ArtistName\":\"The Hillwilliams\",\"City\":\"Tigard\"},
{\"ArtistID\":7,\"ArtistName\":\"Bobo and the Bobbettes\",\"City\":\"Ellensburg\"},
{\"ArtistID\":27,\"ArtistName\":\"Bobo 5\",\"City\":\"Ellensburg\"}
]"
}
It was my controller. Not that it wasn't working but that it wasn't returning what I thought it should be. I was deserializing the data table for the "rows" element, and then deserializing the entire element again. So, the controller wasn't return a json string that jqgrid could actually work with.
It's all working now...
public String getArtists2()
{
using (var ac = new ArtistListingController())
{
ac.Gets();
ac.LoadDatatable();
DataView view = new DataView(ac.Datatable);
DataTable dt = view.ToTable(false, "ArtistID", "ArtistName", "City");
var jsonData = new
{
page=1,
total = 1, // (ac.RecordCount + rows - 1) / rows,
records = ac.RecordCount,
rows = dt //JsonConvert.SerializeObject(dt)
};
return JsonConvert.SerializeObject(jsonData);
}
}
Returning:
{
"page":1,
"total":1,
"records":6,
"rows":[
{
"ArtistID":1,
"ArtistName":"Clayton Knight",
"City":"Tigard"
},
{
"ArtistID":2,
"ArtistName":"Corral Creek Bluegrass",
"City":"Sherwood"
},
{
"ArtistID":3,
"ArtistName":"Never Strangers Band",
"City":"Portland"
},
{
"ArtistID":5,
"ArtistName":"The Hillwilliams",
"City":"Tigard"
},
{
"ArtistID":7,
"ArtistName":"Bobo and the Bobbettes",
"City":"Ellensburg"
},
{
"ArtistID":27,
"ArtistName":"Bobo 5",
"City":"Ellensburg"
}
]
}
Related
I am using datatables for fetcing the data from the controller but the issue is that i have to pass some additional parameter for getting the record from the db but the issue is that when i use the sAjaxSource in the datatable request it automatically send all the parameter with the requst like pagination size , columns and sorting and other details without even mentioning it anywhere but when i use the explict ajax request like this.
ajax: {
type: "POST",
data: {accountID : "45d4f5d4f5d"}
}
it only send this parameter which is mentioned in the data and doesn't send other parameter which get sent by default when the request is made using sAjaxSource.
when i send the request like this it works:
$(function () {
var tableTemplates = $('#Voicemailtable').DataTable({
sAjaxSource: "#Url.Action("VoicemailList", "Voicemail")",
serverSide: true,
bServerSide: true,
bProcessing: true,
processing: true,
columns: [
{
data: null, // <-- This is index column
sortable: false,
autoWidth: false
},
{
data: "context",
sortable: false,
autoWidth: false
},
{
data: "created",
render: function (data) {
return moment(data).format('MM/DD/YYYY hh:mm:ss');
}
}
,
{
data: "guid",
sortable: false,
autoWidth: false
}
,
{
data: "mailbox",
sortable: false,
autoWidth: false
}
,
{
data: "password",
sortable: false,
autoWidth: false
}
,
{
data: "uniqueid",
sortable: false,
autoWidth: false
}
]
});
tableTemplates.on('draw.dt',
function () {
var PageInfo = $('#Voicemailtable').DataTable().page.info();
tableTemplates.column(0, { page: 'current' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + PageInfo.start;
});
});
});
public ActionResult VoicemailList(JqueryDatatableRequestModel model,string accountId)
{
var totalRecords = 0;
var voicemails = voicemailService.GetVoicemailsListByAccountId(accountId, name: model.sSearch, totalCount: out totalRecords, recordStart: model.iDisplayStart, pageSize: model.iDisplayLength);
var finalResults = Mapper.Map<List<VoicemailModel>>(Voicemails);
return Json(new
{
model.sEcho,
iTotalRecords = totalRecords,
iTotalDisplayRecords = totalRecords,
aaData = finalResults
}, JsonRequestBehavior.AllowGet);
}`
but when i try to add the additonal parameter it doesnt work
$(function () {
var table = $('#Voicemailtable').DataTable();
var sEcho = table.settings()[0].oAjaxData.sEcho;
var sSearch = table.search();
var iDisplayLength = table.page.len();
var iDisplayStart = table.page.info().start;
var iSortCol_0 = table.order()[0][0];
var sSortDir_0 = table.order()[0][1];
var tableTemplates = $('#Voicemailtable').DataTable({
sAjaxSource: "#Url.Action("VoicemailList", "Voicemail")",
serverSide: true,
bServerSide: true,
bProcessing: true,
processing: true,
ajax: {
url: '#Url.Action("VoicemailList", "Voicemail")',
type: "Get",
data: {
accountId: "45454-df454-f4d65f4d54f"
sEcho: sEcho,
sSearch: sSearch,
iDisplayLength: iDisplayLength,
iDisplayStart: iDisplayStart,
iSortCol_0: iSortCol_0,
sSortDir_0: sSortDir_0
},
},
columns: [
{
data: null, // <-- This is index column
sortable: false,
autoWidth: false
},
{
data: "context",
sortable: false,
autoWidth: false
},
{
data: "created",
render: function (data) {
return moment(data).format('MM/DD/YYYY hh:mm:ss');
}
}
,
{
data: "guid",
sortable: false,
autoWidth: false
}
,
{
data: "mailbox",
sortable: false,
autoWidth: false
}
,
{
data: "password",
sortable: false,
autoWidth: false
}
,
{
data: "uniqueid",
sortable: false,
autoWidth: false
}
]
});
tableTemplates.on('draw.dt',
function () {
var PageInfo = $('#Voicemailtable').DataTable().page.info();
tableTemplates.column(0, { page: 'current' }).nodes().each(function (cell, i) {
cell.innerHTML = i + 1 + PageInfo.start;
});
});
});
I tried making request from different pattern but its not working if someone could guide my it would be really appriciated.
I'm using jqgrid for my project.
So far, jqgrid is ok while I'm using with ahsx file
But when I try to use [WebMethod] in aspx file, I get error 500.
Here is my jqgrid setting
$(document).ready(function () {
$("#JQGrid").jqGrid({
url: 'Testing.aspx/LoadMachineCapacity',
mtype: 'POST',
ajaxGridOptions: { contentType: 'application/json; charset=utf-8' },
datatype: "json",
postData: {},
height: 100,
autowidth: true,
loadtext: "Loading...",
colModel: [
{
name: 'MACHINEID',
index: 'MACHINEID',
label: 'Machine ID',
sortable: false,
editable: false
},
{
name: 'ISACTIVE',
index: 'ISACTIVE',
label: 'IS ACTIVE',
sortable: false,
editable: true
}],
loadonce: true,
serializeGridData: function (postData) {
return JSON.stringify(postData);
},
multiselect: false,
caption: 'Machines',
pager: '#JQGridPager',
pgbuttons: true, rowNum: 10, rowList: [10, 20, 30],
rownumbers: true,
viewrecords: true
, cellEdit: true
, afterEditCell: function (rowid, cellname, value, iRow, iCol) {
alert(value);
},
loadError: function (jqXHR, textStatus, errorThrown) {
alert('HTTP status code: ' + jqXHR.status + '\n' +
'textStatus: ' + textStatus + '\n' +
'errorThrown: ' + errorThrown + '\n' +
'errorDesc.: ' + jqXHR.responseText);
}
});
$("#JQGrid").navGrid('#JQGridPager',
{ view: false, edit: false, search: true, add: false, del: false, refresh: true }
);
});
and here is my server-side code
[WebMethod]
public static string LoadMachineCapacity(string pageIndex)
{
string Result = "";
try
{
string strOracleCnnString = ConfigurationManager.ConnectionStrings["PKERP"].ConnectionString;
OracleConnection oracleConn = new OracleConnection(strOracleCnnString);
string strSQL = " SELECT * " +
" FROM T_CT_MCCP " ;
OracleDataAdapter dataAdapter = new OracleDataAdapter(strSQL, oracleConn);
DataTable dataTable = new DataTable();
dataAdapter.Fill(dataTable);
Result = JsonConvert.SerializeObject(dataTable, Formatting.Indented);
}
catch (Exception e)
{
Result = JsonConvert.SerializeObject(e.Message, Formatting.Indented);
}
return Result;
}
Thank in advance.
Thomas
There are a parameter at Webmethod.
However, your jqGrid setting not config at postData.
Change to postData: {pageIndex: "blabla"}.
I am using a flexigrid in ASP.NET, I am having trouble binding the JSON data with the flexigrid I get the JSOn response from the web service but it doesn't bind with the grid and doesn't display the grid, Where am I wrong. I am using a webservice to return the JSON data , Here is the code which I am using.Thanks.
My js function to get data from the webservice and bind the json with flexigrid
$(document).ready(function () {
var obj;
$.ajax({
type: "post",
contentType: "application/json",
url: "FlexService.asmx/GetData",
data: "{}",
dataType: 'json',
success: function (result) {
obj = $.parseJSON(result.d);
//add data
$("#FlexTable").flexAddData(formatEmployeeResults(obj));
}
});
//init flexigrid
$("#FlexTable").flexigrid({
dataType: 'json',
colModel: [{display: 'ID', name: 'id', width: 90, sortable: true, align: 'center'},
{display: 'First Name', name: 'fName', width: 120, sortable: true,align: 'left'},
{display: 'Last Name', name: 'lName', width: 120, sortable: true, align: 'left'},
{display: 'Role', name: 'uRole', width: 120, sortable: true, align: 'left'},
{display: 'Salary', name: 'sal', width: 80, sortable: true, align: 'left'}],
searchitems: [{display: 'ID', name: 'id'},
{display: 'First Name', name: 'fName', isdefault: true}],
sortname: "ID",
sortorder: "asc",
usepager: true,
title: 'Employees',
useRp: true,
rp: 15,
showTableToggleBtn: true,
width: 750,
height: 200
});
function formatEmployeeResults(Employee) {
var rows = Array();
for (i = 0; i < Employee.length; i++) {
var item = Employee[i];
rows.push({ cell: [item.id, item.fName, item.lName, item.uRole, item.sal]
});
}
return {total: Employee.length, page: 1, rows: rows}
}
});
My web service code :
public string GetData()
{
List<Employee> lst = new List<Employee>();
string strConn = ConfigurationManager.ConnectionStrings["FlexDb"].ConnectionString;
OleDbConnection cnx = new OleDbConnection(strConn);
OleDbCommand cmd = new OleDbCommand("Flex",cnx);
cnx.Open();
cmd.CommandType = CommandType.StoredProcedure;
OleDbDataReader dataReader = cmd.ExecuteReader();
while (dataReader.Read())
{
Employee e1 = new Employee();
e1.id = Convert.ToInt32(dataReader["USER_ID"]);
e1.fName = dataReader["FIRST_NAME"].ToString();
e1.lName = dataReader["LAST_NAME"].ToString();
e1.uRole = dataReader["USER_ROLE"].ToString();
e1.sal = dataReader["SALARY"].ToString();
lst.Add(e1);
}
var jss = new JavaScriptSerializer();
return jss.Serialize(lst);
}
I tried your example, and it works perfectly. The only thing is that you might have forgotten to add the CSS file link in your head tag. For example:
<link href="Content/flexigrid/flexigrid.css" rel="stylesheet" />
I have a dropdown select column in jqgrid and I am populating the dropdown dynamically from the controller action. When I edit a row and select a value from the drop down and click Submit, it calls the controller action specified in the editurl but the drop down select column value is "undefined". I am stuck with this issue for a while, please any suggestions are really helpful. Below is my javascript code
jQuery("#list").jqGrid({
url: '/Home/Update/',
datatype: 'json',
mtype: 'POST',
colNames: [‘Name’, ‘Position’],
colModel: [
{name: ' Name', index: ' Name', width: 50, align: 'center', editable: true,
searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{name: ' Position ', index: ' Position ', width: 75, align: 'center', editable: true,
edittype: 'select', formatter:'select',
editoptions: {
dataUrl: '/Home/GetNames/',
style: "width: 120px",
buildSelect: function (data) {
var response = $.parseJSON(data);
var s = '<select>';
for (var i = 0; i < response.rows.length; i++) {
var r = response.rows[i];
s += '<option value="' + r.Id + '">' + r.cell[0] + '</option>';
}
return s + "</select>";
}
},
searchoptions: { sopt: ['eq', 'ne', 'cn']} }],
ondblClickRow: function (row_id) {
jQuery(this).jqGrid('editGridRow', row_id);
},
pager: jQuery('#list'),
height: '100%',
rowNum: 200,
sortname: ‘Name’,
sortorder: "asc",
editurl: '/Home/Create'
});
I solved the issue with dataEvents property as below:
dataEvents: [{
type: 'change',
fn: function (e) {
var i = $(e.target.value);
}
}]
Hope this helps someone.
I'm trying to use jqgrid edit form, but I can't understand why jqgrid do not call asmx web method every time I select a row and I click on edit icon (jqgrid call ajax just the first time)
This is the code:
function Grid() {
var ret = Array();
var grid = jQuery("#grid");
var hideLoading = function () {
$("#lui_" + grid).hide();
$("#load_" + grid).hide();
}
var strSearch = "";
var strField = "";
var strOper = "";
//
// handler: si occupa di creare il contenuto del menu a tendina (form jqGrid)
//
var buildOptions = function (dataList) {
var response = dataList;
var option = "";
if (response && response.length) {
for (var i = 0, l = response.length; i < l; i++) {
if (response[i]["selectedvalue"] == "on")
option += '<option role="option" selected="selected" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
else
option += '<option role="option" value="' + response[i]["Codice"] + '">' + response[i]["Descrizione"] + '</option>';
}
}
return option;
};
grid.jqGrid({
// setup custom parameter names to pass to server
prmNames: {
search: "isSearch",
nd: null,
rows: "numRows",
page: "page",
sort: "sortField",
order: "sortOrder"
},
// add by default to avoid webmethod parameter conflicts
postData: {
searchString: '',
searchField: '',
searchOper: ''
},
// setup ajax call to webmethod
datatype: function (postdata) {
$.ajax({
url: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateDiscount") %>',
type: "POST",
contentType: "application/json; charset=utf-8",
data: JSON.stringify(postdata),
dataType: "json",
success: function (data, st) {
if (data.d == "KO") {
grid.GridUnload();
jAlert("La ricerca non ha restituito alcun risultato", "Book2Guest");
return false;
}
if (st == "success") {
var grid = $("#grid")[0];
grid.addJSONData(JSON.parse(data.d));
ret = JSON.parse(data.d);
}
},
error: function (xhr, textStatus, errorThrown) {
jAlert("Si è verificato un errore: " + textStatus + " " + errorThrown + " -- " + $.parseJSON(xhr.statusText), "Book2Guest");
}
});
},
// this is what jqGrid is looking for in json callback
jsonReader: {
root: "rows",
page: "page",
total: "totalpages",
records: "totalrecords",
cell: "cell",
id: "id",
userdata: "userdata",
repeatitems: true
},
ajaxSelectOptions: {
contentType: "application/json; charset=utf-8",
dataType: "json",
cache: false,
data: {
rowId: function () {
if (JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']) == undefined)
return "";
return JSON.stringify(grid.jqGrid('getRowData', grid.jqGrid('getGridParam', 'selrow'))['Codice']);
}
}
},
colNames: ['ID', 'Rate'],
colModel: [
{ name: 'ID', index: 'ID', width: 10, align: "center", search: false, sorttype: 'int', searchoptions: { sopt: ['eq', 'ne', 'cn']} },
{
name: 'TariffaCodiceOfferta',
index: 'TariffaCodiceOfferta',
width: 50,
hidden: true,
formatter: 'select',
editable: true,
edittype: 'select',
editrules: { edithidden: true }, //, required: true },
editoptions: {
multiselect: true,
dataUrl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/GetRoomRateListByRowId") %>',
buildSelect: function (data) {
var response = $.parseJSON(data.d);
var option = buildOptions(response);
var s = '<select>';
s += option;
return s + "</select>";
},
dataInit: function (elem) {
setTimeout(function () {
$(elem).multiselect({ selectedList: 10 });
}, 50);
},
multiple: true
}
},
],
rowNum: 10,
rowList: [10, 20, 30],
height: 'auto',
pager: '#gridpager',
viewrecords: true,
shrinkToFit: false,
loadComplete: function () {
hideLoading();
},
loadError: function () {
hideLoading();
},
editurl: '<%# ResolveUrl("~/Service/Domain/ServiceRoom.asmx/SaveRoomDiscount") %>',
sortname: "ID",
sortorder: "asc",
caption: "Rate list",
onSelectRow: function (id, status) {},
ondblClickRow: function (rowid) {
grid.jqGrid('editGridRow', rowid,
{
width: 450,
height: 450,
closeOnEscape: true,
addCaption: "Add Rate",
editCaption: "Edit Rate",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {
}
});
return;
},
gridComplete: function () {
if (grid.getGridParam('records') == 0) // are there any records?
DisplayEmptyText(true);
else
DisplayEmptyText(false);
},
emptyDataText: 'There are no records. '
})
grid.setGridWidth(900, true);
grid.jqGrid('navGrid', '#gridpager',
{
edit: true,
view: false,
add: false,
del: true,
search: false
},
//prmEdit
{
width: 450,
height: 300,
closeOnEscape: true,
addCaption: "Aggiungi Offerta",
editCaption: "Modifica Offerta",
bSubmit: "Salva",
bCancel: "Annulla",
bClose: "Chiudi",
saveData: "Sono state apportate delle modifiche, sei sicuro di voler continuare?",
bYes: "Si",
bNo: "No",
bExit: "Annulla",
editData: {
"Codice": function () {
var selectedRow = grid.getGridParam("selrow");
var rowData = grid.getRowData(selectedRow);
return rowData["Codice"];
}
},
viewPagerButtons: false,
closeAfterEdit: true,
reloadAfterSubmit: true,
beforeShowForm: function (form) {
var dlgDiv = $("#editmod" + grid[0].id);
var parentDiv = dlgDiv.parent(); // div#gbox_list
var dlgWidth = dlgDiv.width();
var parentWidth = parentDiv.width();
var dlgHeight = dlgDiv.height();
var parentHeight = parentDiv.height();
// Grabbed jQuery for grabbing offsets from here:
//http://stackoverflow.com/questions/3170902/select-text-and-then-calculate-its-distance-from-top-with-javascript
var parentTop = parentDiv.offset().top;
var parentLeft = parentDiv.offset().left;
dlgDiv[0].style.top = Math.round(parentTop + (parentHeight - dlgHeight) / 2) + "px";
dlgDiv[0].style.left = Math.round(parentLeft + (parentWidth - dlgWidth) / 2) + "px";
},
onClose: function (response, postdata) {}
}
//prmSearch,
//prmView
);
return ret;
}
UPDATE: to solve this issue, you guys have to insert 'recreateForm: true' in the edit section of jqGrid
You current code don't have 'Codice' column in colModel, but you try to get the data from the column. Even if the original server response has the Codice property, the property will be saved only if you add additional hidden column with the same name.
Sorry, but to tell the trust I would recommend you to rewrite the whole code which you use. The usage of datatype as function is not good. Instead of that you can use jsonReader. The call JSON.parse(data.d) inside of $.ajax having dataType: "json" shows that you did one more important error in the webmethod on the server side. It shows that you make manual conversion of returned object to String instead of returning object from the web method. WebService convert the object to JSON automatically. Because of manual convention to JSON the returned data will be twice converted to JSON. Only because of the error in the server code you have to use JSON.parse(data.d) and can't just use jsonReader like described here for example.