JqGrid Search In MVC
This is the next part of jqGrid tutorial, before this we already study the basic examples, pagination and sorting of jqGrid. Here we are learning searching feature in jqGrid.
Here we are creating a mvc application for demonstrating jqGrid. That has a controller that name is JqGridController. In that controller, GetStudents() method return the list of records from database table Student using Entity Framework in json format. Index action method is created for ui representation.
Controller Codes
public class JqGridController : Controller
{
//GET: /JqGrid/
public ActionResult Index()
{
return View();
}
public JsonResult GetStudents()
{
DbStudentEntities db = new DbStudentEntities();
var data = from i in db.Students
select new
{
StudentId = i.StudentId,
Name = i.Name,
Mobile = i.Mobile,
Email = i.Email,
City = i.City,
DOJ = i.DOJ
};
return Json(data, JsonRequestBehavior.AllowGet);
}
API References
You can download the jqGrid api package or install the jqGrid packages using NuGet package installer from visual studio. After that add all required scripts on page. Below is showing all necessary reference files.
<link href="~/Scripts/JqGrid/css/ui.jqgrid.css" rel="stylesheet" />
<link href="~/Scripts/Jquery-ui/css/ui-lightness/jquery-ui-1.10.3.custom.css" rel="stylesheet" />
<script src="~/Scripts/JqGrid/js/jquery-1.11.0.min.js"></script>
<script src="~/Scripts/JqGrid/js/jquery.jqGrid.min.js"></script>
Html Codes
Add below html codes
<div>
<table id="tblData"></table>
<div id="divPager"></div>
</div>
js Codes
colModel's searchoptions: Use colModel's searchoptions option for searching facility. That have an option sopt which accept array of string. String is the special keyword for searching text from column. Following are search keywords:
1. eq : equal
2. ne : not equal
3. lt : less
4. le : less or equal
5. gt : greater
6. ge : greater or equal
7. bw : begins with
8. bn : does not begin with
9. in : is in
10. ni : is not in
11. ew : ends with
12. en : does not end with
13. cn : contains
14. nc : does not contain
In below example, we are using 'cn' keyword that means whatever text you enter in textbox, result will be only that who contains that text.
<script type="text/javascript">
$(document).ready(function () {
$("#tblData").jqGrid({
url: 'http://localhost:51548/JqGrid/GetStudents',
datatype: "json",
mtype: 'Get',
colNames: ['Name', 'Mobile', 'Email', 'City'],
colModel: [{ name: 'Name', index: 'Name', sorttype: 'text', searchoptions: {sopt:['cn'
]}
},
{ name: 'Mobile', index: 'Mobile', searchoptions: { sopt: ['cn'] } },
{ name: 'Email', index: 'Email', searchoptions: { sopt: ['cn'] } },
{ name: 'City', index: 'City', searchoptions: { sopt: ['cn'] } }],
width: 700,
height: 'auto',
viewrecords: true,
loadonce: true,
gridview:true,
rowNum: 5,
rowList: [5, 10, 20, 50, 100],
pager: $("#divPager"),
caption: "JqGrid Sample By programidea.com"
});
$("#tblData").jqGrid('filterToolbar', { searchoperators: true });
});