0

I have 2 queries on binding jgGrid in MVC application.. 1. I am unable to bind jsonData which is coming from controller on Success callback method 2. On button click i am loading jqgrid from server data, but when i click 2nd time it is not firing my server code(which is in controller), only first time it is executing the server code.

below is my javascript code

function buildGrid() {

// 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) { mtype: "GET", $.ajax({ url: 'PageName.aspx/getGridData', type: "POST", contentType: "application/json; charset=utf-8", data: JSON.stringify(postdata), dataType: "json", success: function(data, st) { if (st == "success") { var grid = jQuery("#list")[0]; grid.addJSONData(JSON.parse(data.d)); } }, error: function() { alert("Error with AJAX callback"); } }); }, // this is what jqGrid is looking for in json callback jsonReader: { root: "rows", page: "page", total: "totalpages", records: "totalrecords", cell: "cell", id: "id", //index of the column with the PK in it userdata: "userdata", repeatitems: true }, colNames: ['Id', 'First Name', 'Last Name'], colModel: [ { name: 'id', index: 'id', width: 55, search: false }, { name: 'fname', index: 'fname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} }, { name: 'lname', index: 'lname', width: 200, searchoptions: { sopt: ['eq', 'ne', 'cn']} } ], rowNum: 10, rowList: [10, 20, 30], pager: jQuery("#pager"), sortname: "fname", sortorder: "asc", viewrecords: true, caption: "Grid Title Here" }).jqGrid('navGrid', '#pager', { edit: false, add: false, del: false }, {}, // default settings for edit {}, // add {}, // delete { closeOnEscape: true, closeAfterSearch: true}, //search {} ) });

 var grid = $("#jQGrid"); $("#jQGrid").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: {
        'ddlDSVIN': function () {
            return $('#ddlDevice :selected').val();
        },
        'search': function () { return $("#searchId").val(); },
        'OEMType': function () { return $('#ddlOEM :selected').text(); },
        'frmDate': function () { return fromDate.toDateString(); },
        'toDate': function () { return toDate.toDateString(); }

    },
    datatype: function(postdata) { mtype: "POST",
        $.ajax({ url: '/DataIn/DataInSearchResult/', type: "POST", contentType: "application/json; charset=utf-8", 
        //data: postData,
        datatype: "json",
        success: function(data, st) {
            if (st == "success") {
                var grid = jQuery("#jQGrid")[0]; grid.addJSONData(JSON.parse(data.d));
                var container = grid.parents('.ui-jqgrid-view');
                $('#showgrid').show();
                $('#jQGrid').show();
                $('#divpager').show();
                //container.find('.ui-jqgrid-hdiv, .ui-jqgrid-bdiv').show();
                $("#hideandshow").show();
                $("#lblTotal").html($(this).getGridParam("records") + " Results");
                $("#hideandshow2").hide();
            }
        },
        error: function(error) { alert("Error with AJAX callback" + error); } }); }, // this is what jqGrid is looking for in json callback 
    jsonReader: { root: "rows", page: "page", total: "totalpages", records: "totalrecords", cell: "cell", id: "id", //index of the column with the PK in it
        userdata: "userdata", repeatitems: true
    },

   // url: '/DataIn/DataInSearchResult/',



    colNames: ["PayloadCorrelationId", "Asset", "Type", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],

    colModel: [
        { name: 'CorrelationId', index: 'CorrelationId', jsonmap: 'CorrelationId', hidden: true, width: 2, key: true },
       // { name: "", index:'', editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "True:False" }, formatoptions: { disabled: false } },
        { name: 'Device', jsonmap: 'Device', width: '65px' },
        { name: 'Type', jsonmap: 'Type', width: '65px' },
        { name: 'DateReported', jsonmap: 'DateReported', width: '100px' },
          { name: 'ErrorType', jsonmap: 'ErrorType', width: '85px' },
   { name: 'Error', jsonmap: 'Error', width: '160px' },
   { name: 'Latitude', jsonmap: 'Latitude', width: '78px' }, { name: 'Longitude', jsonmap: 'Longitude', width: '78px' },
   { name: 'Payloadurl', jsonmap: 'Payloadurl', width: '180px', formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } }],

          rowNum: 10, rowList: [10, 20, 30],
          pager: jQuery("#divpager"),  sortorder: "asc",
            viewrecords: true, caption: "Grid Title Here"
 }).jqGrid('navGrid', '#divpager', { edit: false, add: false, del: false }, {}, // default settings for edit
 {}, // add
  {}, // delete


{ closeOnEscape: true, closeAfterSearch: true}, //search
    { }); 
}

above method is called in document.ready function $(documen).ready(function() {

("#buttonclick").click(function() {

buildGrid();
});

});

Can you please what was wrong with my code.. because i need to search on button click by passing the paramerter's to service method using postData {},but how to send this postData to url and bind the result to JqGrid.

thanks

Raj.

Kalu Singh Rao
  • 1,671
  • 1
  • 16
  • 21
Rajneesh
  • 2,009
  • 2
  • 12
  • 6
  • sorry, but first of all I don't recommend you don't use ever `datatype` defined as function where you just make `$.ajax` call. All examples which you would find in the style are created for very old versions of jqGrid and there provides wrong code. You can use `datatype: "json"` instead and to use `url` option of jqGrid. You can make additional customization of the server response in `jsonReader.root` or inside of `beforeProcessing` callback. It saves a lot of unneeded work which you have to do (and which you don't do currently) inside of `datatype` function. – Oleg Feb 26 '16 at 09:56
  • please can u provide sample code of above, correcting the wrong line of code, bcz i m new to jqgrid. even i don't understand what you mean to say.. as i am beginner to jqgrid and its structure and properties... – Rajneesh Feb 28 '16 at 17:36
  • I posed modified code in my answer. I don't know the exact format of the response of data which you use from `url: '/DataIn/DataInSearchResult/'`. It could be that additional modification is required. Moreover it could be important *which version and from which fork* of jqGrid you use. I' recommend you to use [free jqGrid](https://github.com/free-jqgrid/jqGrid) 4.13.0. It's the fork of jqGrid, which I develop. Moreover you can consider to use `loadonce: true` scenario. It's good if **the total number of rows** of grid is not so large (for example <1000 rows). – Oleg Feb 28 '16 at 20:10

1 Answers1

0

Usage of datatype as is not recommend way. Instead of that one can use datatype: "json". It informs that jqGrid should make for you the Ajax request using $.ajax method. One can use additional options of jqGrid to specify the options of the underlying $.ajax request.

The next problem you have in the code

$(documen).ready(function() {
    $("#buttonclick").click(function() {
        buildGrid();
    });
});

The function buildGrid will be called every time if the user click on #buttonclick button. The problem is that you have initially the empty table

<table id="jQGrid"></table>

on your page, but after creating the grid (after the call $("#jQGrid").jqGrid({...});), the empty table will be converted in relatively complex structure of dives and tables (see the picture). The second call on non-empty table will be just ignored by jqGrid. It's the reason why the 2nd click on the button #buttonclick do nothing.

You can solve the problem in two ways. The first would be including $("#buttonclick").jqGrid("GridUnload"); before creating the grid. It would be destroy the grid and recreate the initial empty table. The second way os a little better. You can not destroy the grid at the second time, but to call $("#buttonclick").trigger("reloadGrid"); instead. It will force making new Ajax request to the server.

Minimal changing of your original code will follow us to about the following:

$(documen).ready(function() {
    var $grid = $("#jQGrid");

    $grid.jqGrid({ 
        //setup custom parameter names to pass to server 
        prmNames: {
            search: "isSearch",
            nd: null,
            rows: "numRows",
            sort: "sortField",
            order: "sortOrder"
        },
        // add by default to avoid webmethod parameter conflicts 
        postData: {
            ddlDSVIN: function () {
                return $('#ddlDevice').val();
            },
            search: function () {
                return $("#searchId").val();
            },
            OEMType: function () {
                return $('#ddlOEM')
                    .find("option")
                    .filter(":selected")
                    .text();
            },
            frmDate: function () {
                return fromDate.toDateString();
            },
            toDate: function () {
                return toDate.toDateString();
            }
        },
        mtype: "POST",
        url: '/DataIn/DataInSearchResult/',
        datatype: "json",
        ajaxGridOptions: { contentType: "application/json; charset=utf-8" },
        loadComplete: function () {
            $('#showgrid').show();
            $('#jQGrid').show();
            $('#divpager').show();
            $("#hideandshow").show();
            $("#lblTotal").html($(this).getGridParam("records") + " Results");
            $("#hideandshow2").hide();
        },
        jsonReader: {
            root: root: function (obj) {
                return typeof obj.d === "string" ?
                    $.parseJSON(obj.d) :
                    obj.d;
            },
            total: "totalpages",
            records: "totalrecords"
        },
        colNames: ["PayloadCorrelationId", "Asset", "Type", "DateReported", "ErrorType", "Error", "Latitude", "Longitude", "Payloadurl"],
        colModel: [
            { name: 'CorrelationId', hidden: true, width: 2, key: true },
            // { name: "", index:'', editable: true, edittype: "checkbox", width: 45, sortable: false, align: "center", formatter: "checkbox", editoptions: { value: "True:False" }, formatoptions: { disabled: false } },
            { name: 'Device', width: 65 },
            { name: 'Type', width: 65 },
            { name: 'DateReported', width: 100 },
            { name: 'ErrorType', width: 85 },
            { name: 'Error', width: 160 },
            { name: 'Latitude', width: 78 },
            { name: 'Longitude', width: 78 },
            { name: 'Payloadurl', width: 180, formatter: 'showlink', formatoptions: { baseLinkUrl: 'javascript:', showAction: "Link('", addParam: "');" } }],
        rowNum: 10,
        rowList: [10, 20, 30],
        pager: "#divpager",
        sortorder: "asc",
        viewrecords: true,
        caption: "Grid Title Here"
    }).jqGrid('navGrid', '#divpager', { edit: false, add: false, del: false },
        {}, // default settings for edit
        {}, // add
        {}, // delete
        { closeOnEscape: true, closeAfterSearch: true} //search
    );

    $("#buttonclick").click(function() {
        $grid.trigger("reloadGrid");
    });
});
Oleg
  • 220,925
  • 34
  • 403
  • 798