Mapping data to JQGrid with Ajax call - ajax

I'm just trying to display a very simple JQGrid with data from an ajax call to a controller. All I'm seeing is the grid headers, no data. Can someone please help me figure out what I'm doing wrong? Thanks in advance!
Here's the Ajax call and JQGrid setup..
$("#grid").jqGrid({
url: '#Url.Action("GetLoanReport", "Report")',
datatype: "json",
height: "auto",
colNames: ['Name', 'Random Stuff'],
colModel: [
{ name: 'Name', index: 'Name', width: 150, sortable: true },
{ name: 'RandomStuff', index: 'RandomStuff', width: 500, sortable: false }
],
jsonReader: {
repeatitems: true,
root: 'rowdata',
page: 'currpage',
total: 'totalpages',
records: 'totalrecords'
},
rowNum: 10,
rowList: [5, 10, 30],
rownumbers: false,
gridview: true,
loadonce: true,
pager: "#page",
caption: "Flat Data Example"
});
Here's the controller code...
Function GetLoanReport() As JsonResult
ViewData("Ribbon") = "partials/_statsRibbon"
Dim response As New Response
Dim model As New ReportModel
model.Name = "Mark"
model.RandomStuff = "Highfield"
response.currpage = 1
response.totalpages = 1
response.totalrecords = 1
response.rowdata = model
Return Json(response, JsonRequestBehavior.AllowGet)
End Function

The main problem: rowdata should be array of items (array of objects) instead of one object only with Name and RandomStuff properties.
Additionally you should decide whether you implement server side paging of data or you want to return all the data from GetLoanReport at once and jqGrid should make local paging, sorting and filtering/sorting the data? In the case you should use loadonce: true option. Additionally it's important to choose the fork of jqGrid, which you use: free jqGrid, commercial Guriddo jqGrid JS or an old jqGrid in version <=4.7. I develop free jqGrid fork, which I can recommend you. If you use it, then I would recommend you to add forceClientSorting: true option additionally to loadonce: true. It will allows you to use sortname and sortorder options to sort the data returned from the server before it will be displayed.

Related

How to access id of onSelectRow in delOptions action method in jqGrid

//Hidden Input element
//my grid details:
$("#jqGrid").jqGrid({
url: '#Url.Action("EditedEventData", "Calendar" ,new{ })' + '?CountryId=' + #countryid + '&CityId=' + #cityid ,
async: true,
datatype: "json",
colModel: [
//label: "Edit Actions",
name: "",
width: 100,
formatter: "actions",
formatoptions: {
keys: true,
edit: true,
add: true,
del: true,
editOptions: {},
addOptions: {},
delOptions: {
url:'#Url.Action("RemoveEvent", "Calendar")'+ '?HolidayId='+document.getElementById('hdnEventId').value ,
//mtype: 'POST',
}// **here it is showing hdnEventId value empty**
}
}
],
onSelectRow : function(id){
console.log('inside onSelectRow');
alert(id);
document.getElementById('hdnEventId').value=id;
alert(document.getElementById('hdnEventId').value);
},
sortname: 'EventDate',
loadonce: true,
width: 750,
height: 200,
rowNum: 150,
pager: "#jqGridPager"
});
I am unable to access id of onSelectRow in delOptions action method.
So thought of taking a hidden html element and store the value but it is showing empty.
Thanks in advance
When a delete is performed the id is automatically send to the server. The parameter which is obtained via post is named id.
If you additionally want to fill a id on deleting a rows you can use some events to fill the field you want. These are described here. In the same documentation see the chapter What is posted to the server .
To fill the id in another field when a row is deleted I think the good choice is to use either serializeDelData or afterSubmit events - see the events on the same link.
When use these events the parameter postdata contain the id. By example in serializeDelData (set this in delOptions) this can look like
serializeDelData : function( postdata ) {
var id = postdata.id;
document.getElementById('hdnEventId').value=id;
return postdata;
}
Remember both events should return some params

jqGrid Trying to apply filter(s) on Grid creation

I have an object that contains the following filter string:
prefs.filters={"groupOp":"AND","rules":[{"field":"FirstName","op":"cn","data":"max"}]}
Here is my grid create, where I am trying to apply the filters in the postData setting:
// Set up the jquery grid
$("#jqGridTable").jqGrid(
{
// Ajax related configurations
url: jqDataUrl,
datatype: "json",
mtype: "GET",
autowidth: true,
// Configure the columns
colModel: columnModels,
// Grid total width and height
height: "100%",
// customize jqgrid post init
gridComplete: function()
{
CRef.updateJqGridPagerIcons("jqGridTable");
},
// Paging
toppager: true,
rowNum: 20,
rowList: [5, 10, 20, 50, 100],
viewrecords: true, // Specify if "total number of records" is displayed
// Default sorting
sortname: typeof prefs.sortCol !== "undefined" ? prefs.sortCol : "LastName",
sortorder: typeof prefs.sortCol !== "undefined" ? prefs.sortOrd : "asc",
sorttype: "text",
sortable: true,
postData: typeof prefs.filters !== "undefined" ? { filters: prefs.filters } : {},
//also tried this...
//postData: typeof prefs.filters !== "undefined" ? { JSON.stringify(filters: prefs.filters) } : {},
//remaining property settings excluded from post to keep short.
Update: Using .navGrid on grid as follows:
.navGrid("#jqGridTable",
{ refresh: true, add: false, edit: false, del: false, refreshtitle: getRefreshText('#Model.Instruction'), searchtitle: searchText },
{}, // settings for edit
{}, // settings for add
{}, // settings for delete
{ closeAfterSearch: true, closeOnEscape: true, multipleSearch: true, multipleGroup: true });
When grid is created, the filter in postData is not applied. I also tried triggering reload event after the initial create and that to did not apply filter either.
From other posts, I believe I'm on correct path, but appear to be missing something.
Update after comments:
I added the following code to loadComplete...
if ($("#jqGridTable").jqGrid("getGridParam", "datatype") === "json") {
setTimeout(function () {
$("#jqGridTable").jqGrid("setGridParam", {
datatype: "local",
postData: { filters: prefs.filters, sord: prefs.sortOrd, sidx: prefs.sortCol },
search: true
});
$("#jqGridTable").trigger("reloadGrid");
}, 50);
}
and it successfully retains the filters. :)
However, now I have interesting issue side effect. I can sort on columns and some columns will change to sort asc/desc correctly, but when I go to others and sort, they sort but in the order that they originally loaded which is neither asc or desc.
You have to set search: true option of jqGrid if you want that filters will be applied. Moreover you use datatype: "json". It means that the filters will be just send to the server and your server code have to decode the filters and to use there. One more remark. The correct value for postData would be { filters: JSON.stringify(prefs.filters) }.
UPDATED: I recommend you upgrade to the latest version (4.12.1) or free jqGrid. It's the fork of jGrid which I develop since the end of 2014. To use free jqGrid you can just change the URLs to jqGrid files to URLs described in the wiki article. After that you can use the following options:
loadonce: true,
forceClientSorting: true,
search: true,
postData: { filters: prefs.filters },
sortname: prefs.sortCol,
sortorder: prefs.sortOrd
and remove the loadComplete code which you posted in "Update after comments" part of your question. Free jqGrid will load all data returned from the server, apply the filter prefs.filters locally, sort the results locally and display the first page of the results (based on the page size rowNum: 20).
The old demo loads the JSON data from the server, sort the data locally and filter by isFinal === 1 and finally display the first page of results. The demo uses additionally custom sorting using sortfunc, additionalProperties, which allows to saved additionally properties in local data.
You can additionally include reloadGridOptions: { fromServer: true } to other options of navGrid which you use (refresh: true, add: false, ...). It will change the behavior of the Refresh button of the navigator bar to reload the data from the server if the user clicks on the button. See another answer, which I posted today for more information about new options of free jqGrid and loadonce: true.

Grid view in mvc6

How to add grid view in MVC-6?
I would like to use webgrid something for listing the details. Is it possible to use System.Web.Helpers as namespace. But I am not getting it supporting
This project could fit your requirements, a simple grid control for ASPNET MVC (using Razor): MVC6.Grid.Web
You can also try NetCoreControls.
Built specifically for .NET MVC Core.
The Grid Control is server side, uses AJAX, and supports, paging, filter and events.
Check the documentation and demo website.
You can use the Shield UI for ASP.NET Core NuGet package and integrate it with the free Shield UI Lite via Bower, or the commercial Shield UI suite.
Their Grid widget is awesome!
I would suggest to use the jqGrid(or may be some other java scripts grid). From the MVC controller return the ActionResult as JSON object
public ActionResult UserList()
{
object userListData = null;
try
{
List<UserListViewModel> users = 'your code to get the user list'
userListData = new
{
page = 1,
records = users.Count,
rows = users
};
}
JavaScriptSerializer serializer = new JavaScriptSerializer();
serializer.MaxJsonLength = int.MaxValue;
return new ContentResult()
{
Content = serializer.Serialize(userListData),
ContentType = "application/json",
};
}
and call this on page load/jQuery document Ready some thing like this.
$("#userTable").jqGrid({
url: '../User/UserList,
mtype: 'GET',
datatype: "json",
autowidth: true,
colNames: ['Id', 'First Name', 'Last Name'],
colModel: [
{ name: 'Id', key: true, hidden: true, fixed: false, shrinkToFit: false, align: 'left' },
{ name: 'FirstName', fixed: false, shrinkToFit: false, align: 'left' },
{ name: 'LastName', fixed: false, shrinkToFit: false, align: 'left' }
],
for more information about jqGrid, please see demo at http://jqgrid.com/

jqGrid : searchrules in single Field searching

I'm trying to validate the search field for integer data alone but unfortunately am unable to do so. I have tried all possible solutions like searchrules:{required:true,integer=true} etc..
But none of them proves fruitful.
I basically launch the search dialog with the field and without inputting any data, am hitting on the 'Find' button. As per the above options, i believe a validation message should be shown to the user asking him to enter a value in the field before hitting find.
[UPDATED] - Code Snippet
var grid = $("#list");
grid.jqGrid({
url:'/index.jsp',
datatype: 'json',
mtype: 'POST',
colNames:['Name','Age', 'Address'],
colModel :[
{name:'name', index:'name', width:55,search:true },
{name:'age', index:'age',
width:90,editable:true,search:true, stype:'text',
searchrules:{required:true,integer:true}},
{name:'address', index:'address', width:80,
align:'right', editable: true,search:false }
],
pager: '#pager',
jsonReader : {
root:"address",
page: "page",
total: "total",
records: "records",
repeatitems: false
},
rowNum:10,
rowList:[10,20,30],
sortname: 'name',
sortorder: 'desc',
viewrecords: true,
gridview: true,
autowidth: true,
toppager: true,
loadtext: "Loading records.....",
caption: 'Test Grid',
gridComplete: function(){
}
});
**grid**.jqGrid('navGrid','#pager',
{view:true,edit:true,add:true,del:true,refresh:true,
refreshtext:'Refresh',addtext:'Add',
edittext:'Edit',cloneToTop:true,
edittitle: "Edit selected row"},
{},{},{},
{caption: "Search The Grid",Find: "Find Value",Reset: "Reset"},
{});
[Updated] : Am not able to make the searchrules properly work for the single/advanced searching modes.
[Updated] : Even the 'Validation in Search' in
jqGrid Demo is not working for searchrules.
The reason of described problem is a bug in jqGrid. The line
ret = $.jgrid.checkValues(val, -1, null, colModelItem.searchrules, colModelItem.label);
initialize the third parameter of $.jgrid.checkValues to null, but the last version of checkValues implementation started (see the line) with
var cm = g.p.colModel;
but g is initialized to null. The last modification which generates the error was based on my suggestion, but I don't wrote the part of the code.
One can solve the problem in different way. I would suggest to modify the line where $.jgrid.checkValues will be called with null parameter to the following
ret = $.jgrid.checkValues(val, -1, {p: {colModel: p.columns}}, colModelItem.searchrules, colModelItem.label);
Additionally, to be sure, I would suggest to modify one more line
if(!nm) { nm = g.p.colNames[valref]; }
to
if(!nm) { nm = g.p.colNames != null ? g.p.colNames[valref] : cm.label; }
The fixed version of jquery.jqGrid.src.js one can get here. I will post my bug report with the same suggestions later ti trirand.

customize: POST output in jqGrid without changing source file?

I'm trying to turn jqGrid within MODx, as do other data exchange using "$. ajax", move the call from a URL to a resource protected by a password and from there call a snippet of code in PHP, so the security framework, the ajax call is guaranteed
This is one example of a chunk $.ajax:
$.ajax ({
url :'[[~94]]',
type: 'post',
async: false,
success: function(rsp) {
$.Cookie("xxxxxx-tipodirlist", rsp);
}
});
*[[~94]] is a protected resource is within a snippet call [[!SnpBridgedata_blabla]]
the system works perfectly well throughout the web application, receiving and sending data safely and securely.
Now a customer asked me for a completed application wanted web results in a good grid and after seeing a bit of code I decided to use jqGrid for my project.
integration was quick and I am very happy to have changed "DataTable" with "jqGrid," but when I finished the test, change the absolute path to xxxxxx.php with the call to snippet
this is the code for jqGrid:
chargeSedi function (idx)
{
// Test with file. Php !work fine!
// Var esURL = 'http://xxxxx.com/xxxxxxx.php?IDX =' + idx;
// Test with MODx resource !not work!
esURL var = '[[~ 97]] & IDX =' + idx;
csURL var = '[[~ 96]] & IDX =' + idx;
tipodirlist = $ var. cookie ("xxxxxxxx-tipodirlist");
tiposedelist = $ var. cookie ("xxxxxxx-tiposedelist");
$("#sediTable").ready(function() {
$("#sediTable").jqGrid({
url:csURL,
datatype: "json",
height: 250,
autowidth:true,
colNames:[ 'ID','CODICE', 'NOME','TDIR', 'DIR','COMUNE', 'PROVINCIA','CAP', 'TSEDE','NOTA'],
colModel:[
{name:'ID',index:'ID', width:25, editable: false},
{name:'CODICE',index:'CODICE', width:60, editable: true},
{name:'NOME',index:'NOME', width:60, editable: true},
{name:'TDIR',index:'TDIR', width:60, editable: true,edittype:"select",editoptions:{value:tipodirlist}},
{name:'DIR',index:'DIR', width:200, sortable:false,editable: true},
{name:'COMUNE',index:'COMUNE', width:170, sortable:false,editable: true},
{name:'PROVINCIA',index:'PROVINCIA', width:170, sortable:false,editable: true},
{name:'CAP',index:'CAP', width:40, sortable:false,editable: true},
{name:'TSEDE',index:'TSEDE', width:90, editable: true,edittype:"select",editoptions:{value:tiposedelist}},
{name:'NOTA',index:'NOTA', width:170, sortable:false,editable: true,edittype:"textarea", editoptions:{rows:"2",cols:"10"}} ],
sortname: 'ID',
viewrecords: true,
sortorder: "desc",
loadonce: true,
editurl: esURL ,
caption: "Sedi" });
});
]
and for my surprise the MODx deny Access to jqGrid ajax calls, as if you were out of session, but after hours testing and watching the traffic with wireshark I realized that jqGrid sends a POST variable called "id" and call MODx a GET variable "id". this in other environments is possible without problem, but it is not possible MODx and there's the problem.
my question is how I can change the name of the POST variable "id" jqGrid, without changing the source of jqGrid?
at the same time wanted to ask, you can customize the import of a select the value and not the index
example of trame POST:
{Name: 'TDIR', index: 'TDIR', width: 60, editable: true, EditType: "select" editoptions: {value: tipodirlist}}
tipodirlist = 1:via;2:piazza;3:ect
TDIR=2
CODICE=1&NOME=principale&TDIR=2&DIR=Roma&COMUNE=Torino&PROVINCIA=Torino&CAP=10000&TSEDE=2&NOTA=NO=edit&id=0
for this:
TDIR=piazza
CODICE=1&NOME=principale&TDIR=piazza&DIR=Roma&COMUNE=Torino&PROVINCIA=Torino&CAP=10000&TSEDE=2&NOTA=NO=edit&id=0
without having to filter the results on the server.
I hope I've explained well and clear. as I asked myself, the team "StackOverflow" before asking this question
Thank you so much
Regards
niro.
PS.I hope that GOD "Oleg" help me:)
I don't know and don't use MODx. Nevertheless I hope that your problem is: how to rename the name of the id parameter to have no conflict with the id parameter used by MODx.
If I understand your question correct you should just add additional prmNames parameter which set the new name of id parameter used in editing operations:
prmNames: {id: 'myId'}
The example will rename the default id parameter name ({id: "id"}) to myId which you should you in your server part.

Resources