title: How do you add column search filter on JqGrid on sever-side code?
body: <p>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 <a href="http://mvcjqgrid.skaele.it/Home/Search" rel="nofollow">this</a></p>
  
  <p>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:</p>
  
  <p>[Not a real link used for example]</p>
  
  <pre><code>http://local/Home/CallGrid?_search=true&amp;nd=1388596935527&amp;rows=10&amp;page=1&amp;sidx=&amp;sord=asc&amp;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
  </code></pre>
  
  <p>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:</p>
  
  <p><strong>Query Parameter</strong></p>
  
  <pre><code>Parameter          Value
  
  _search                true
  
  nd           1388537724720
  
  rows      10
  
  page      1
  
  sidx       
  
  sord       asc
  
  filters    {"groupOp":"AND","rules":[{"field":"EmailAddress","op":"bw","data":"p"}]}
  </code></pre>
  
  <p><strong>Content</strong></p>
  
  <pre><code>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"}]}
  </code></pre>
  
  <p>My only conclusion is that I have to add <code>QueryStringParameter</code> 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. </p>
  
  <p>I believe the main area to fix this json search/filter issue will  be in the controller here's what the controller looks like:</p>
  
  <pre><code>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&lt;NamedQueryCallInfo&gt; 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&lt;NamedQueryCallInfo&gt; queryList1 = nhbQuery.SetResultTransformer(NHibernate.Transform.Transformers
  
  .AliasToBean(typeof(NamedQueryCallInfo))).List&lt;NamedQueryCallInfo&gt;();
  
  
  
          /*
  
                      //------------------
  
           * var context = new HaackOverflowDataContext();
  
                      var context = new HaackOverflowEntities();
  
                      var serializer = new JavaScriptSerializer();
  
                      Filters f = (!_search || string.IsNullOrEmpty(filters)) ? null : serializer.Deserialize&lt;Filters&gt;(filters);
  
                      ObjectQuery&lt;NamedQueryCallInfo&gt; 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 =&gt; r.field == "CallTransDate") ?
  
              //    DateTime.ParseExact(settings.Where.rules.FirstOrDefault(r =&gt; r.field == "CallTransDate").data,
  
              //               "M/d/yyyy", null) : DateTime.MinValue;
  
  
  
              filter.Service = settings.Where.rules.Any(r =&gt; r.field == "CallTransTypeDesc") ?
  
                  settings.Where.rules.FirstOrDefault(r =&gt; r.field == "CallTransTypeDesc").data : string.Empty;
  
              filter.Service = settings.Where.rules.Any(r =&gt; r.field == "CallTransCodeDesc") ?
  
                  settings.Where.rules.FirstOrDefault(r =&gt; r.field == "CallTransCodeDesc").data : string.Empty;
  
              filter.Service = settings.Where.rules.Any(r =&gt; r.field == "CallTransSiteLocation") ?
  
                  settings.Where.rules.FirstOrDefault(r =&gt; r.field == "CallTransSiteLocation").data : string.Empty;
  
              filter.Service = settings.Where.rules.Any(r =&gt; r.field == "AgentIdentifier") ?
  
                  settings.Where.rules.FirstOrDefault(r =&gt; r.field == "AgentIdentifier").data : string.Empty;
  
          }
  
              //string x = settings.SortOrder;
  
              //string  y = settings.SortColumn;
  
  
  
  
  
          // NamedQueryCallInfo customerRepository = new  NamedQueryCallInfo();
  
  
  
  
  
          //--IList&lt;NamedQueryCallInfo&gt; 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&lt;NamedQueryCallInfo&gt;().Select(c =&gt; c);
  
          IEnumerable&lt;NamedQueryCallInfo&gt; 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);
  
      }
  </code></pre>
  
  <hr>
  
  <p>Here's what my view looks like:</p>
  
  <pre><code>@(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);}")
  
  
  
  
  
   )
  </code></pre>
  
  <p><strong>Script</strong></p>
  
  <pre><code>&lt;script type="text/javascript"&gt;
  
  
  
      /*
  
      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 });
  
  
  
  &lt;/script&gt;
  </code></pre>