09 August 2015

Changing JQGRID URL dynamically

While developing web applications, there will be need sometimes to render the data in JQGRID, based on what customer want to see it. But in JQGRID, the URL will provided for the first time when you created the JQGRID like below:

jQuery("#customerGrid").jqGrid({
          
    url: "/Customer/GetByType/3"
    datatype: 'json'
});

With the hard coded the URL, cannot render different data based on what user want to see it. If you need to display different data by changing URL, with the above hard coded URL approach, you end up recreating the JQGRID every time. I think that is expensive, considering that, need is to change just the URL form which data will be fetched.

One option is to consider changing just the URL, depending on what user what to see it. When you want to display data from a different URL, you need to do two things:

  1. First, change the jqgrid URL
  2. Second, reload the grid

Code to change the jqgrid URL

$("#customerGrid").jqGrid(
'setGridParam',{ url: "/Customer/GetByType/" + $('#customerType').val() 
}).trigger("reloadGrid");
});

Making JQGrid not to load data, just upon constructing it

Sometimes when you want to show data in jqgrid, you might not know the URL upfront to get the JSON data until user selects something. In such scenario, if you mention the URL while constructing the jqGRID, the JQGRID will try to load the data from the URL mentioned, that may not be desirable in some scenarios.

In such scenario, you can stop JQGRID making the URL request for the data. To do this you can do two things:

  1. First mention 'datatype' param as 'local' while building the jqgrid instead on 'json'. Then the 'URL' param mentioned doesn't have any impact.

    jQuery("#customerGrid").jqGrid({
                datatype: 'json'
    });
  2. Second, when user changes the selection to view specific data, change the 'datatype' param to 'json', set the URL to fetch the data and reload the grid.

    $("#customerGrid").jqGrid('setGridParam', { datatype: 'json' }); 

    $("#customerGrid").jqGrid(
        'setGridParam',{ url: "/Customer/GetByType/" +
         $('#customerType').val() 
    }).trigger("reloadGrid");
    });

No comments:

Post a Comment