How to implement search on jqgrid?

I recently implemented this myself (yesterday actually) for the first time. The biggest hurdle for me was figuring out how to write the controller function. The function signature is what took me the longest to figure out (notice the _search, searchField, searchOper, and searchString parameters as those are missing from most of asp.net mvc examples I've seen). The javascript posts to the controller for both the initial load and for the search call. You'll see in the code that I'm checking whether the _search parameter is true or not.

Below is the controller and the javascript code. My apologies for any formatting issues as this is my first time posting on here.

public ActionResult GetAppGroups(string sidx, string sord, int page, int rows, bool _search, string searchField, string searchOper, string searchString)
{
    List<AppGroup> groups = service.GetAppGroups();
    List<AppGroup> results;
    if (_search)
       results = groups.Where(x => x.Name.Contains(searchString)).ToList();
    else
       results = groups.Skip(page * rows).Take(rows).ToList();

    int i = 1;

    var jsonData = new
    {
        total = groups.Count / 20,
        page = page,
        records = groups.Count,
        rows = (
            from appgroup in results
            select new
            {
                i = i++,
                cell = new string[] {
                         appgroup.Name,
                         appgroup.Description
                     }
            }).ToArray()
    };

    return Json(jsonData);
}

And here is my HTML/Javascript:

$(document).ready(function() {
  $("#listGroups").jqGrid({
    url: '<%= ResolveUrl("~/JSON/GetAppGroups/") %>',
    datatype: 'json',
    mtype: 'GET',
    caption: 'App Groups',
    colNames: ['Name', 'Description'],
    colModel: [
        { name: 'Name', index: 'Name', width: 250, resizable: true, editable: false},
        { name: 'Description', index: 'Description', width: 650, resizable: true, editable: false},
    ],
    loadtext: 'Loading Unix App Groups...',
    multiselect: true,
    pager: $("#pager"),
    rowNum: 10,
    rowList: [5,10,20,50],
    sortname: 'ID',
    sortorder: 'desc',
    viewrecords: true,
    imgpath: '../scripts/jqgrid/themes/basic/images'
//});
}).navGrid('#pager', {search:true, edit: false, add:false, del:false, searchtext:"Search"});

See my article on codeproject, which explains how we can do multiple search in jqgrid:

Using jqGrid’s search toolbar with multiple filters in ASP.NET MVC

I use IModelBinder for grid's settings binding, expression trees for sorting and filtering data.


In case you're still wondering about dealing with optional parameters, just declare them as nullables by adding a ? after the type name.

Now you'll be able to compare them with null to check if they are absent.

Note that you don't need to do this with strings, as they are already nullable.