Search code examples
javascriptjqueryheaderjqgrid

How to pass a Token to Request Headers in JQGrid


My project is in ASP Net Core with MVC.

I have a JQGrid in a view. It is working perfectly. Now I have to authorize the Controller using an attribute to pass a JWT to the HttpContext Request Header. In standard Ajax, I know that the headers attribute will take care of the task, but in JqGrid, how would one set the headers?

My code looks like this:

 $("#jqgrid").CreateGrid({
            url: "/api/fares/getfares",
            headers: { "Authorization": 'Bearer ' + '@Model.JWToken' },                
            colNames: ['Id', 'From', 'To', 'Date', 'Airline', 'FlightNo', 'Dep.Time', 'Arr.Time'],
            colModel: [..........],
            pager: '#pjqgrid',
            sortname: 'Id',
            sortorder: "desc",
            loadonce: false,
            rows: 1,
            container: $('#div_jqgrid_container'),                
            loadingText: 'Loading..',
            noRecordText: 'No Records found',
        }, $("#jqgrid"));

The above code works, but not sending the Authorization header. Some one please extend some help !!!


Solution

  • Thanks, finally I got it. Add the option loadBeforeSend as a function in hte jqGrid code body like this. Now it works like a charm !

    $("#jqgrid").CreateGrid({
            url: "/api/fares/getfares",
            // headers: { "Authorization": 'Bearer ' + '@Model.JWToken' },                
            loadBeforeSend: function (jqXHR) {
                jqXHR.setRequestHeader("Authorization", 'Bearer ' + '@Model.JWToken' );
            },
            colNames: ['Id', 'From', 'To', 'Date', 'Airline', 'FlightNo', 'Dep.Time', 'Arr.Time'],
            colModel: [..........],
            pager: '#pjqgrid',
            sortname: 'Id',
            sortorder: "desc",
            loadonce: false,
            rows: 1,
            container: $('#div_jqgrid_container'),                
            loadingText: 'Loading..',
            noRecordText: 'No Records found',
        }, $("#jqgrid"));
    

    ps: If anybody would like the full code, please comment here and I shall post the complete jqGrid details.