How do you add column search filter on JqGrid on sever-side code?

1.5k views Asked by At

I'm passing Json data to the JqGrid table through my controller? I want paging and sorting to be done through my controller as well as filter/search.This is a dynamic search-filter so searchOnEnter = false. I don't want loadonce = true because it will stop paging/sorting, but it will enable client-side filter/search. I want my filter search to work like this

Whenever I type data to any column's search-feild in my Jqgrid, I'm able to receive json get request. For example, when I type "Kei" in to the search textbox of the Name colunm in the JqGrid table, I receive a GET application/json request that looks something like this:

[Not a real link used for example]

http://local/Home/CallGrid?_search=true&nd=1388596935527&rows=10&page=1&sidx=&sord=asc&filters=%7B%22groupOp%22%3A%22AND%22%2C%22rules%22%3A%5B%7B%22field%22%3A%22Name%22%2C%22op%22%3A%22bw%22%2C%22data%22%3A%22Kei%22%7D%5D%7D

The problem that I'm having is that the current data on my json table is not being filtered by the GET application/json request. I'm using Firefox to due my debugging. For example if i type 'p' on the email column the content of the query-parameter and json content looks like what's below but nothing ever get filtered:

Query Parameter

Parameter          Value

_search                true

nd           1388537724720

rows      10

page      1

sidx       

sord       asc

filters    {"groupOp":"AND","rules":[{"field":"EmailAddress","op":"bw","data":"p"}]}

Content

Type: application/json

{"total":2,"page":1,"records":14,"filters":"{\"groupOp\":\"AND\",\"rules\":
[{\"field\":\"CallTransTypeDesc\",\"op\":\"bw\",\"data\":\"p\"}]}","SortColumn":"",
"SortOrder":"asc","rows":[{"CallTransTypeDesc":"Customer Service",
"CallTransCodeDesc":"ANSWER QUESTION/RESENT KIT",
"CallTransSiteLocation":"Houston, TX","AgentIdentifier":"ROKUNEYE"},
{"CallTransTypeDesc":"Customer Service","CallTransCodeDesc":
"CROSS SELL NOT OFFERED CSV","CallTransSiteLocation":"Houston, TX",
"AgentIdentifier":"ROKUNEYE"},
{"CallTransTypeDesc":"Customer Service","CallTransCodeDesc":
"TRV/FRM/COMPANION TICKET","CallTransSiteLocation":"Westerville, OH",
"AgentIdentifier":"JAALLEN"},
{"CallTransTypeDesc":"Customer Service","CallTransCodeDesc":
"TRV/RBT/$40 GAS COUPON","CallTransSiteLocation":"Westerville, OH",
"AgentIdentifier":"JAALLEN"},
{"CallTransTypeDesc":"Customer Service","CallTransCodeDesc":
"CROSS SELL NOT ACCEPTED CSV","CallTransSiteLocation":"Westerville, OH",
"AgentIdentifier":"JAALLEN"},
{"CallTransTypeDesc":"Customer Service","CallTransCodeDesc":
"30 DAYS TERM EXTENSION","CallTransSiteLocation":"Westerville, OH",
"AgentIdentifier":"JAALLEN"},
{"CallTransTypeDesc":"Save","CallTransCodeDesc":"BENEFIT ONLY SAVE",
"CallTransSiteLocation":"Westerville, OH","AgentIdentifier":"JAALLEN"},
{"CallTransTypeDesc":"Save","CallTransCodeDesc":"BENEFIT ONLY SAVE",
"CallTransSiteLocation":"Westerville, OH","AgentIdentifier":"JAALLEN"},
{"CallTransTypeDesc":"Fulfillment","CallTransCodeDesc":null,
"CallTransSiteLocation":
"Westerville, OH","AgentIdentifier":"JAALLEN"},
{"CallTransTypeDesc":"Fulfillment","CallTransCodeDesc":null,
"CallTransSiteLocation":
"Westerville, OH","AgentIdentifier":"JAALLEN"}]}

My only conclusion is that I have to add QueryStringParameter of C# Class into my controller so that I can get the json filtered parameter from my url into part of the controller that deals with passing the json data. But I'm not to sure on how I would do this. Any suggestion and references would be greatly appreciated.

I believe the main area to fix this json search/filter issue will be in the controller here's what the controller looks like:

public JsonResult CallGrid(GridSettings settings, string sord, string sidx, bool _search, NamedQueryCallInfo filter, string filters)

        {



        // Controller for Grid  code to work on view  TranHistViewGrid.cshtml

       //string rice = settings.SortColumn;

        //  string wice =  settings.SortOrder





        //Gets the Referer Header string url string

        Uri MyUrl = Request.UrlReferrer;



        // repersents data for the postService value found above in the Referer url

        string postService = HttpUtility.ParseQueryString(MyUrl.Query).Get("postService");



        // repersents data for the postMemberId value found above in the Referer url

        string postMemberId = HttpUtility.ParseQueryString(MyUrl.Query).Get("postMemberId");



        // repersents data for the postJoinDate value found above in the Referer url

        string postJoinDate1 = HttpUtility.ParseQueryString(MyUrl.Query).Get("postJoinDate");

        DateTime postJoinDate = Convert.ToDateTime(postJoinDate1);





        //Nhibernate code Connection to obtain query.



        NhbHelper.NHibernateHelperBizin nbh;

        nbh = new NhbHelper.NHibernateHelperBizin();

        ISession nhbSession = NHibernateHelperBizin.GetCurrentSession();

        ITransaction nhbTransaction = nhbSession.BeginTransaction();

        //IQueryable<NamedQueryCallInfo> customers = null;

       // NamedQueryCallInfo customerRepository = new  NamedQueryCallInfo();

        IQuery nhbQuery = nhbSession.GetNamedQuery("NamedQueryCallInfo");



        nhbQuery.SetParameter("queryparamContractId", postMemberId);

        nhbQuery.SetParameter("queryparamService", postService);

        nhbQuery.SetParameter("queryparamJoinDate", postJoinDate);



        //queryList instantiate query value to pass vaules in the query code mapped to database

        IList<NamedQueryCallInfo> queryList1 = nhbQuery.SetResultTransformer(NHibernate.Transform.Transformers

.AliasToBean(typeof(NamedQueryCallInfo))).List<NamedQueryCallInfo>();



        /*

                    //------------------

         * var context = new HaackOverflowDataContext();

                    var context = new HaackOverflowEntities();

                    var serializer = new JavaScriptSerializer();

                    Filters f = (!_search || string.IsNullOrEmpty(filters)) ? null : serializer.Deserialize<Filters>(filters);

                    ObjectQuery<NamedQueryCallInfo> filteredQuery =

                        (f == null ? context.Questions : f.FilterObjectSet(context.Questions));

                    filteredQuery.MergeOption = MergeOption.NoTracking;

                    //------------------------------

        */

      //  NamedQueryCallInfo filter = new NamedQueryCallInfo();

       // var orderedCustomers = OrderCustomers(customers, settings.SortColumn, settings.SortOrder);



        if (settings.IsSearch)

        {







            // filter.CallTransDate = settings.Where.rules.Any(r => r.field == "CallTransDate") ?

            //    DateTime.ParseExact(settings.Where.rules.FirstOrDefault(r => r.field == "CallTransDate").data,

            //               "M/d/yyyy", null) : DateTime.MinValue;



            filter.Service = settings.Where.rules.Any(r => r.field == "CallTransTypeDesc") ?

                settings.Where.rules.FirstOrDefault(r => r.field == "CallTransTypeDesc").data : string.Empty;

            filter.Service = settings.Where.rules.Any(r => r.field == "CallTransCodeDesc") ?

                settings.Where.rules.FirstOrDefault(r => r.field == "CallTransCodeDesc").data : string.Empty;

            filter.Service = settings.Where.rules.Any(r => r.field == "CallTransSiteLocation") ?

                settings.Where.rules.FirstOrDefault(r => r.field == "CallTransSiteLocation").data : string.Empty;

            filter.Service = settings.Where.rules.Any(r => r.field == "AgentIdentifier") ?

                settings.Where.rules.FirstOrDefault(r => r.field == "AgentIdentifier").data : string.Empty;

        }

            //string x = settings.SortOrder;

            //string  y = settings.SortColumn;





        // NamedQueryCallInfo customerRepository = new  NamedQueryCallInfo();





        //--IList<NamedQueryCallInfo> customerRepository = null;

          //  var customers = customerRepository.ToArray(filter, settings.SortColumn, settings.SortOrder, settings.PageIndex );







        //ReplicationMode ytr = new ReplicationMode();

      //  CallGrid(GridSettings r, sord, sidx);

        int count = queryList1.Count();  //--- number of total items from query

        int page = settings.PageIndex;

        int totalPages = (int)Math.Ceiling((double)count / settings.PageSize);



        // CallGrid(); try to take out the sord and sidx above

        var questions = queryList1;

        /*

        customers = customerRepository.CallGrid(filter,

                                         settings.SortColumn,

                                         settings.SortOrder,

                                         settings.PageSize,

                                         settings.PageIndex,

                                         out totalPages);

       */





        // instantiation that gives varable data test the ability to act like linq and convert query data to Json data.

        var test = questions.AsQueryable<NamedQueryCallInfo>().Select(c => c);

        IEnumerable<NamedQueryCallInfo> sortedRecords = test.ToList();



        //sortedRecords = orderedCustomers.sortedRecords;



        if (sord == "desc")

            //string w = settings.SortOrder;



            sortedRecords = sortedRecords.Reverse();

        sortedRecords = sortedRecords.Skip((settings.PageIndex - 1) * settings.PageSize).Take(settings.PageSize).ToArray();





        //----------------------

        var result = new

        {

            total = totalPages, //--- number of pages

            page,               //--- current page

            records = count,    //--- total items

            //filters,







            rows = (from p in sortedRecords

                    select new

                    {

                      //  CallTransDate = p.CallTransDate.ToShortDateString(),

                        CallTransTypeDesc = p.CallTransTypeDesc,

                        CallTransCodeDesc = p.CallTransCodeDesc,

                        CallTransSiteLocation = p.CallTransSiteLocation,

                        AgentIdentifier = p.AgentIdentifier,



                    }).ToArray()




        };







        return Json(result, JsonRequestBehavior.AllowGet);

    }

Here's what my view looks like:

@(Html.Grid("search")

.SetCaption("Jq-Grid Call View")

//.SetLoadUi(MvcJqGrid.Enums.LoadUi.Enable)

.SetRequestType(RequestType.Get)

.SetViewRecords(true)

 //  .AddColumn(new Column("CallTransDate")

 //   .SetLabel("Call Date").SetSearch(true).SetSearchType(MvcJqGrid.Enums.Searchtype.Datepicker).SetSearchDateFormat("M/d/yyyy").SetSearchOption(MvcJqGrid.Enums.SearchOptions.Equal))

.AddColumn(new Column("CallTransTypeDesc").SetLabel("Call Type Desc").SetSearch(true).SetSearchOption(SearchOptions.BeginsWith))

.AddColumn(new Column("CallTransCodeDesc").SetLabel("Call Code Desc").SetSearch(true).SetSearchOption(SearchOptions.BeginsWith).SetSortable(true))

.AddColumn(new Column("CallTransSiteLocation").SetLabel("Call Site Location").SetSearch(true).SetSearchOption(SearchOptions.BeginsWith))

.AddColumn(new Column("AgentIdentifier").SetLabel("Agent Identifier").SetSearch(true).SetSearchOption(SearchOptions.BeginsWith))

.SetUrl(Url.Action("CallGrid", "Kore"))

// .SetUrl("~/Home/TranHistViewGrid")

.SetAutoEncode(true)

.SetDataType(DataType.Json)

.SetJsonReader(jsonReader)

.SetLoadUi(LoadUi.Block)

.SetAutoWidth(true)

.SetSortOnHeaderClick(true)

.SetRowList(new[]{10,15,20,50})

//.SetSearchClearButton(true)

.SetRowNum(10)

.SetToolbar(true)

.SetSearchToolbar(true).SetSearchOnEnter(false)

  .SetShowAllSortIcons(true)

 .SetShrinkToFit(true)

 .SetIgnoreCase(true)

 .SetPager("pager")

 .OnLoadBeforeSend("addGridSearchOption")

 .SetGridView(true)

 //.OnSerializeGridData("function (data) {return JSON.stringify(data);}")





 )

Script

<script type="text/javascript">



    /*

    jQuery(document).ready(function () {



        $("#search").setGriddParam({ datatype: 'json', page: 10 }).trigger('reloadGrid');

    }

    ); */





    function addGridSearchOption(grid, fieldName, fieldValue) {

        if (grid[0].p.search == false) {

           f = { groupOp: "AND", rules: [] };

            f.rules.push({ field: fieldName, op: "bw", data: fieldValue });

            grid[0].p.search = true;

            $.extend(grid[0].p.postData, { filters: JSON.stringify(f) });

        }

        else {

            tFilters = eval('(' + grid[0].p.postData.filters + ')');

            var bAddRule = true;

            var i = 0;

            for (var tRule in tFilters.rules) {

                if (tFilters.rules[i].field == fieldName) {

                    tFilters.rules[i].data = fieldValue;

                    bAddRule = false;

                }

                i++;

            }

            if (bAddRule) {

                tFilters.rules.push({ field: fieldName, op: "bw", data: fieldValue });

            } grid[0].p.postData.filters = JSON.stringify(tFilters);



        }

    }







/*

    function processrequest(postdata) {



        $.ajax({



            complete: function (jsondata, stat) {

                if (stat == "success") {

                    var thegrid = jQuery("#list2")[0];

                    var jsonObject = (eval("(" + jsondata.responseText + ")"));

                    thegrid.addJSONData(jsonObject.d);

                    $(".loading").hide();

                } else {

                    $(".loading").hide();

                    alert("Error with AJAX callback");

                }

                $("#search").setGridParam({ datatype: 'local' });

            }

        });

    }

    */

    //jQuery("#search").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false });



</script>
1

There are 1 answers

0
CodeNewbie On BEST ANSWER

i think you need to use this line of command in your server side codes.

jQuery("#list10").jqGrid('filterToolbar', { stringResult: true, searchOnEnter: false });