Load local data to JqGrid with paging, sorting and toolbar searching

Hi friends, again i have came up with new article on JqGrid. In past i had written couple of articles.

  1. Get the data from WCF service and assign it to Jqgrid
  2. Get the data from asp.net handler(ashx) and assign it to Jqgrid

But this article is bit different, after reading this you would have a good idea how to assign local data to a jqgrid. You can create own json data and use that. Also you would gain idea for searching, sorting and paging.
Local Data jQGrid
The complete demo is here.
Follow the steps below to create jqgrids

  1. Please download the demo, there you can find the folders css and js. Both the folders are having all the js css file needed for jqgrid.
  2. Add an html file and add the js and css file references to this page.
  3. Please refer the UserList.html file to setup the JqGrid

Below attributes and the values are needed to load the local data
1) datatype
2) datastr
3) jsonReader

Local data Jqgrid
Refer the Screen shot above for visual guidance

Please check the jqgrid definition below:

$(function() {
	//Get the all the data needed for Jqgrid
	//GetAllUsers() method is defined in the UserData.js file
    //This "data" is a global variable and 
	//it is assigned to the "datastr" attribute in Jqgrid definition
	var data = new GetAllUsers();

	$("#UsersGrid").jqGrid({
		//We need 3 attributes to use the local data
		//1) datatype 2) datastr 3) jsonReader
		datatype: 'jsonstring',
		datastr: data,
		//Used to read the data from json object and assign to JqGrid
		jsonReader: {
			root: "rows",
			page: "page",
			total: "total"
		},
		height: 200,
		width: 800,
		//Define your columns Here.
		colNames: ['UserId', 'Name', 'BirthPlace', 'Color'],
		colModel: [ { name: 'UserId', index: 'UserId', width: 100, sorttype: 'integer' },
					{ name: 'Name', index: 'Name', width: 200, sorttype: 'string' },
					{ name: 'BirthPlace', index: 'BirthPlace', width: 200, sorttype: 'string' },
					{ name: 'Color', index: 'Color', width: 100, sorttype: 'string' }
				  ],
		rowNum: 10,
		rowList: [10, 20, 30],
		//This property is very usefull.
		loadonce: true,
		pager: '#UsersGridPager',
		sortname: 'UserId',
		viewrecords: true,
		sortorder: 'asc',
		sortable: true,
		//Change your table name
		caption: 'User Information',
		//Ignore Case while searching
		ignoreCase: true
	});
	jQuery("#UsersGrid").jqGrid('filterToolbar', {
		searchOperators: false,
		searchOnEnter: false,
		autosearch: true,
		defaultSearch: 'cn'
	});
});

You can create your custom Json data to use in JqGrid. Please have a sample codes below:

//Creating user
function User(userId, name, birthPlace, color) {
    this.UserId = userId;
    this.Name = name;
    this.BirthPlace = birthPlace;
    this.Color = color;
}

//This method/constructor would create an object, that jqgrid can receive the data 
function GetAllUsers() {
    var listOfUsers = [];
    listOfUsers[0] = new User(1, "Sibasis Jena", "Bhubaneswar", "Blue");
    listOfUsers[1] = new User(2, "Malaya Sahoo", "Jaggannath Prasad", "Red");
    listOfUsers[2] = new User(3, "Bimal Das", "Kolkata", "Red");
    listOfUsers[3] = new User(4, "Susangeet", "Cuttack", "Black");
    listOfUsers[4] = new User(5, "Tadit Dash", "Nayagarh", "green");
    listOfUsers[5] = new User(6, "Deepak Jena", "Baleswar", "Red");
    listOfUsers[6] = new User(7, "Sisir Jena", "Bhanjanagar", "Blue");
    listOfUsers[7] = new User(8, "Bhikari Nayak", "Bhanjanagar", "Red");
    listOfUsers[8] = new User(9, "Narayan Badhei", "Jaggannath Prasad", "Red");
    listOfUsers[9] = new User(10, "Nalini", "Bhanjanagar", "Red");
    listOfUsers[10] = new User(11, "Lucky", "Aska", "Gray");
    listOfUsers[11] = new User(12, "Jitendra", "Jaggannath Prasad", "LightGray");
    listOfUsers[12] = new User(13, "Bhikari Sahu", "Madhabarida", "Black");
    listOfUsers[13] = new User(14, "Bhaja Jena", "Delhi", "Black");
    listOfUsers[14] = new User(15, "Lingaraj Barik", "Nayagarh", "green");
    listOfUsers[15] = new User(16, "Kumar singh", "Bhanjanagar", "Red");
    listOfUsers[16] = new User(17, "Manas Ranjan", "Bhanjanagar", "Blue");
    listOfUsers[17] = new User(18, "Biswajit", "Bhanjanagar", "Red");
    listOfUsers[18] = new User(19, "Sidhanta", "Jaggannath Prasad", "Red");
    listOfUsers[19] = new User(20, "Akshya", "Bhanjanagar", "Red");
    listOfUsers[20] = new User(21, "Kunumunu", "Bhubaneswar", "Blue");
    listOfUsers[21] = new User(22, "Basant", "Jaggannath Prasad", "Red");
    listOfUsers[22] = new User(23, "Ajit", "Kolkata", "Red");
    listOfUsers[23] = new User(24, "Bulu", "Cuttack", "Black");
    listOfUsers[24] = new User(25, "Gulu", "Nayagarh", "green");
    listOfUsers[25] = new User(26, "DJ jena", "Baleswar", "Red");
    listOfUsers[26] = new User(27, "Prafula", "Bhanjanagar", "Blue");
    listOfUsers[27] = new User(28, "Shivam", "Bhanjanagar", "Red");
    listOfUsers[28] = new User(29, "Narayan Jena", "Jaggannath Prasad", "Red");
    listOfUsers[29] = new User(30, "Vikram", "Bhanjanagar", "Red");
    listOfUsers[30] = new User(31, "Mangulu", "Aska", "Gray");
    listOfUsers[31] = new User(32, "Keshab", "Jaggannath Prasad", "LightGray");
    listOfUsers[32] = new User(33, "Himansu", "Madhabarida", "Black");
    listOfUsers[33] = new User(34, "Jitu", "Delhi", "Black");
    listOfUsers[34] = new User(35, "Satya narayan", "Nayagarh", "green");
    listOfUsers[35] = new User(36, "Uttam", "Bhanjanagar", "Red");
    listOfUsers[36] = new User(37, "Lokanath", "Bhanjanagar", "Blue");
    listOfUsers[37] = new User(38, "Jaga", "Bhanjanagar", "Red");
    listOfUsers[38] = new User(39, "Nilamani", "Jaggannath Prasad", "Red");
    listOfUsers[39] = new User(40, "Tarun Behera", "Bhanjanagar", "Red");
    listOfUsers[40] = new User(41, "Bijay", "Kukudakhandi", "Red");
	
    this.rows = listOfUsers;
    this.page = 1;
    this.total = listOfUsers.length / 10;
}

A simple demo Jqgrid

The jqgrid is filled by Ajax enabled webservice.
Steps:
–Add an ASP.NET Web Application. Automatically a project will be added.
–Add a new Web Form to this project and name this page as “gridcontainer.aspx”
–Add A new project and select WCF Service Application to the existing solution. And name this as MyService.
–Add a new WCF Service(Ajax-enabled) service to Myservice project. Automatically it will add a new service having name as Service2.svc
–Add a Global.asax file to this service.
Here is the total project A simple demo Jqgrid
Please download the project and run the Database scripts in for the table and the procedure.
Please insert some records into the table yourself

Service2.svc.cs content:

using System;
using System.Collections.Generic;
using System.Configuration;
using System.Data;
using System.Data.SqlClient;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;
using System.Text;

namespace MyService
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service2
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public string GetName()
        {
            // Add your operation implementation here
            return "Sibasis";
        }

        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List GetCompanyList()
        {
            DataTable table = new DataTable("Company");
            SqlConnection con=null;
            List lstCo = new List();

            try
            {
                using (con = new SqlConnection(ConfigurationManager.ConnectionStrings["sibasis"].ConnectionString))
                {
                    con.Open();
                    using ( SqlCommand cmd = new SqlCommand("GetAllCompany", con))
                    {
                        using ( SqlDataAdapter adapter = new SqlDataAdapter(cmd))
                        {
                            adapter.Fill(table);
                        }
                    }
                }

                foreach (DataRow row in table.Rows)
                {
                    Company cmp = new Company();
                    cmp.Id = Convert.ToInt32(row["ID"]);
                    cmp.Name = Convert.ToString(row["Name"]);
                    cmp.Country = Convert.ToString(row["Country"]);
                    cmp.State = Convert.ToString(row["State"]);
                    cmp.Language = Convert.ToString(row["Language"]);

                    lstCo.Add(cmp);
                }
        }
            catch (Exception ex)
            {
                throw ex;
            }
            return lstCo;
        }

        [DataContract]
        public class Company
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Country { get; set; }
            [DataMember]
            public string State { get; set; }
            [DataMember]
            public string Language { get; set; }
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

Add the following codes to the Global.asax file in the Myservice project.

protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Add the following code in the Myservice web.config file

 <endpointBehaviors>
        <behavior name="MyService.Service2AspNetAjaxBehavior">
          <enableWebScript />
          <webHttp/>
        </behavior>
      </endpointBehaviors>

Then you are ready with the Jqgrid.

Reload Jqgrid on button click

Reload Jqgrid

Call this function on the button click.

Javascript code:
Note:Replace tbSubscriptionGrid with your own Jqgrid id

function ReloadGrid()
{
$("#tbSubscriptionGrid").jqGrid("setGridParam", { datatype: "json" })
 .trigger("reloadGrid", [{ current: true }]);
}

Html code for button:

<input id="btnReload" onclick="ReloadGrid()" type="button" value="button" />

Reference this link for any more information:JqGrid don’i reload after click on the button

Fill JqGrid using Ajax enabled web service.

You can get the project hereindex
If you want to see a demo the go here trirand.com.
Then click on the Searching tab >Toolbar with Operations

This is pretty simple to fill a jqgrid.
1.Create a simple Project with ASP.NET Web application.
2.Add a WCF Service Application to this solution.
3.Make a slightly modification to your web.config in the wcfservice project

   <endpointBehaviors>
        <behavior name="WcfService1.Service2AspNetAjaxBehavior">
          <enableWebScript />
          <webHttp/>
        </behavior>
      </endpointBehaviors>

4.Add an Web Service(Ajax enabled) in the wcfservice project.
Service2.svc
content goes here

using System.Collections.Generic;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Activation;
using System.ServiceModel.Web;

namespace WcfService1
{
    [ServiceContract(Namespace = "")]
    [AspNetCompatibilityRequirements(RequirementsMode = AspNetCompatibilityRequirementsMode.Allowed)]
    public class Service2
    {
        // To use HTTP GET, add [WebGet] attribute. (Default ResponseFormat is WebMessageFormat.Json)
        // To create an operation that returns XML,
        //     add [WebGet(ResponseFormat=WebMessageFormat.Xml)],
        //     and include the following line in the operation body:
        //         WebOperationContext.Current.OutgoingResponse.ContentType = "text/xml";
        [OperationContract]
        public void DoWork()
        {
            // Add your operation implementation here
            return;
        }
        [OperationContract]
        [WebInvoke(Method = "GET", ResponseFormat = WebMessageFormat.Json, BodyStyle = WebMessageBodyStyle.WrappedRequest)]
        public List GetCompanyList()
        {
            // Add your operation implementation here
            List lstCo = new List();
            for (int i = 0; i < 20; i++)
            {
                Company cmp= new  Company();
                cmp.Id=1;
                cmp.Name="test";
                cmp.Country = "test";
                cmp.State = "test";
                cmp.Language = "test";
                lstCo.Add(cmp);
            }
            return lstCo;
        }

        [DataContract]
        public class Company
        {
            [DataMember]
            public int Id { get; set; }
            [DataMember]
            public string Name { get; set; }
            [DataMember]
            public string Country { get; set; }
            [DataMember]
            public string State { get; set; }
            [DataMember]
            public string Language { get; set; }
        }

        // Add more operations here and mark them with [OperationContract]
    }
}

2. Add a Global.asax file.
add the following code to Global.asax file

 protected void Application_BeginRequest(object sender, EventArgs e)
        {
            HttpContext.Current.Response.AddHeader("Access-Control-Allow-Origin", "*");
            if (HttpContext.Current.Request.HttpMethod == "OPTIONS")
            {
                HttpContext.Current.Response.AddHeader("Cache-Control", "no-cache");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Methods", "GET, POST");
                HttpContext.Current.Response.AddHeader("Access-Control-Allow-Headers", "Content-Type, Accept");
                HttpContext.Current.Response.AddHeader("Access-Control-Max-Age", "1728000");
                HttpContext.Current.Response.End();
            }
        }

Then you are ready to go