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 small angular JS application, calls a WCF service

If you are new to angular js application, then this demonstration would help you a lot.

In below demo, i have used some angular js directive.
DirectiveName
{
width:30%;
}

ng-app By adding this, we declare the scope of the angular js application. This means the application starts here.

ng-controller This handles the application.
ng-model This binds the input values to the application data.
ng-disableed This is used to enable/disable a html control.
ng-click This handles the click event.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title>My Angular demo</title>
</head>
<body>
    <div ng-app="LoginApp" ng-controller="LoginCtrl">
        <input type="text" ng-model="user.firstName" />
        <input type="text" ng-model="user.lastName" />
        <input type="submit" ng-click="Login()" value="Login" ng-disabled="!user.firstName && !user.lastName" />
        {{status}}
        {{!user.firstName}}

    </div>
    {{status}}
    <script src="js/angular.min.js"></script>
    <script>
        var app = angular.module("LoginApp", []);
        app.controller("LoginCtrl", function ($scope, $http) {
            $scope.Login = function () {
                if ($scope.user.firstName != "" && $scope.user.lastName != "") {
                    $http.get("Login.svc/IsUserExist?firstName=" + $scope.user.firstName + "&lastName=" + $scope.user.lastName)
                        .success(function (result) {
                            $scope.status = result.d;
                            if (result.d) {
                                alert("The user is exist in server");
                            }
                        });

                }

            }
        });
    </script>
</body>
</html>

OnItemCommand is not fired ListView C#, ASP.NET

I worked in ListView. And i faced one issue with OnItemCommand. There is link button, on click this button OnItemCommand event shoud fire. But it is not working. Because there is no PostBack check in the Page_Load event. By adding IsPostBack, this issue will be resolved.

Aspx Code:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="MyListViewTest.aspx.cs" Inherits="IgroupUploader.MyListViewTest" %>

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
     <asp:ListView ID="lvFile" runat="server" OnItemCommand="lvFile_ItemCommand" GroupItemCount="2" GroupPlaceholderID="groupPlaceholder">
        <LayoutTemplate>
        <table>
            <tr>
                <td runat="server" id="groupPlaceholder"></td>
            </tr>
          </table>
        </div>
        </LayoutTemplate>

        <GroupTemplate>
            <tr>
            <asp:PlaceHolder runat="server" ID="itemPlaceholder"></asp:PlaceHolder>
            </tr>
        </GroupTemplate>
        <GroupSeparatorTemplate>
           <tr><td style="height:23px;"></td></tr>
        </GroupSeparatorTemplate>
        <ItemTemplate>
            <td>
                <asp:LinkButton ID="LinkButton1" CommandName="Delete" runat="server" Text='<%#Eval("OriginalFileName")  %>' >LinkButton</asp:LinkButton>
              </td> 
        </ItemTemplate>
    </asp:ListView>
    </div>
    </form>
</body>
</html>

Code Behind:

 protected void Page_Load(object sender, EventArgs e)
        {
                    GetFileList();

        }

 public void GetFileList()
        {
            DataTable dtFile = new DataTable();
            DataAccessLayer ObjData = new DataAccessLayer();

            //Get all the files uploaded by the logged in user.
            dtFile = ObjData.GetAllFiles(UserHashCode, this.IsAdmin);
            //Bind it to the listview.
            lvFile.DataSource = dtFile;
            lvFile.DataBind();
        }

        protected void lvFile_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Delete"))
            {
                
            }
            
        }

Every thing is fine in the front end. We have to add not IsPostBack in the page load:

Working Code

 protected void Page_Load(object sender, EventArgs e)
        {
                     if (!IsPostBack)
            {
                
                    GetFileList();

            }

        }

 public void GetFileList()
        {
            DataTable dtFile = new DataTable();
            DataAccessLayer ObjData = new DataAccessLayer();

            //Get all the files uploaded by the logged in user.
            dtFile = ObjData.GetAllFiles(UserHashCode, this.IsAdmin);
            //Bind it to the listview.
            lvFile.DataSource = dtFile;
            lvFile.DataBind();
        }

        protected void lvFile_ItemCommand(object sender, ListViewCommandEventArgs e)
        {
            if (e.CommandName.Equals("Delete"))
            {
                
            }
            
        }

background-size property is not working in ie8 and ie7

Yes background-size is not working in IE 8 and IE 7. Because the background-size property is a CSS3 property.

Bellow CSS working fine in Chrome, Firefox and all IE version greater than 9. And bellow piece of code will not work in IE7 and IE8.

.headerlinkunsel {
background-image: url("../Images/unsel-tab.gif");
background-repeat: repeat-x;
color: #ffffff;
font-size: 12px;
height: 20px;
text-align: left;
text-decoration: none;
background-size:cover;
}

To get this issue resolved in IE8 and IE7, i have followed bellow steps.

Step 1. Download the backgroundsize.min.htc file. Please click here to download.

Step 2. And put the backgroundsize.min.htc file in the same path where your page is placed.

Step 2. Write the bellow style to focus only IE version bellow 9

<!--[if lt IE 9]>
      
        .headerlinksel {
        background-image: url("../Images/sel-tab.gif");
        background-repeat: repeat-x;
        color: #ffffff;
        font-size: 12px;
        padding-left: 4px;
        text-align: left;
        text-decoration: none;
        background-size:cover;
        behavior: url('backgroundsize.min.htc');
        }
<![endif]-->

Please put your valuable comment, if this seems to be helpful for you.

What is WCF binding and Different Types of binding available.

What is WCF binding?
The binding in the config file tells you the bellow information
1. Binding element describing the transport protocol
2. Binding element that handles message encoding.

A binding should have one binding element, which should have the above 2 information.

BasicHttpBinding
This binding obeys the WS-I Basic Profile 1.1. This communicates using ASMX based web services.
WSHttpBinding
This binding follows the WS-* specifications. It supports distributed transactions, and secure, reliable sessions. This communicates using both HTTP and HTTPS transport Protocol. Messages are transmitted in the form of XML text or Message Transmission Optimization Mechanism (MTOM).
WSDualHttpBinding
Represents a binding that a WCF service can use to configure and expose endpoints that are able to communicate with ASMX-based Web services and clients and other services that conform to the WS-I Basic Profile 1.1
WSFederationBinding
This binding supports the WS-Federation specification. WS-Federation defines several models for providing federated security, based on the WS-Trust, WS-Security, and WS-Secure Conversation specifications.
NetTcpBinding
The name itself is saying that it uses the TCP protocol for communication. It uses binary encoding wile transfering messages. It offers higher performance than the bindings based on the HTTP protocols but less interoperability. It supports transactions, reliable sessions, and secure communications.
NetPeerTcpBinding
This binding supports peer-to-peer communications between applications using the TCP protocol. This binding supports secure communications and reliable, ordered delivery of messages. Messages are transmitted by using a binary encoding.
NetNamedPipeBinding
This binding is very helpful for processes running on a same computer. It gives high performance by using named pipes. This binding supports secure, reliable sessions and transactions. You cannot use this binding to connect to a service across a network.
NetMsmqBinding
The client and service can communicate using Microsoft Message Queue (MSMQ).Messages are stored in a message queue, so the client and the service do not both have to be running at the same time. This binding supports secure, reliable sessions and transactions. Messages use a binary encoding.
MsmqIntegrationBinding
You can build an WCF application, that sends or receives messages from an MSMQ message queue. It is intended for use with existing applications that use MSMQ message queues.

Different types of WCF Contracts

By this article, we will get to know all contracts available in WCF
The contracts will let the client know regarding the functionality, the service provide. In WCF we need one interface and we can add all the Contracts inside the interface.

There are 4 types of contracts:

  1. ServiceContract
  2. OperationContract
  3. DataContract
  4. DataMember

You can get the ServiceContract and OperationContract WCF attribute classes in the System.ServiceModel namespace.
You can get the DataContract and DataMember classes are in the System.Runtime.Serialization namespace.
These classes are used to define the details of the contract that your service will have with calling clients.

ServiceContract:By adding the ServiceContract attribute class in the interface, we are telling the that you are a WCF service

OperationContract: If we need to expose a method to the client. Then We need to add this contrat to that particular method.

DataContract:The DataContract attribute class is added to mark that type (classes,
enumerations, or structures) serializable.
DataMember:The DataMember attribute class is used to mark individual fields
and properties that you want to serialize. You use this class with the DataContract class.

How to create a simple WCF service and consume it

Bellow i have explained how to create a simple WCF service in Visual Studio 2013
1. Click on new Project
New Project
2. From the left hand side of the templates please select WCF then you will get a list of templates associated with WCF.
select Template
3. Please select WCF service Application from the list. By default our visual studio will add one Interface and one svc file.
The interface will be have bellow contracts:

  1. ServiceContract
  2. OperationContract
  3. DataContract
  4. DataMember

it looks like bellow:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace MyService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the interface name "IService1" in both code and config file together.
    [ServiceContract]
    public interface IService1
    {

        [OperationContract]
        string GetData(int value);

        [OperationContract]
        CompositeType GetDataUsingDataContract(CompositeType composite);

        // TODO: Add your service operations here
    }


    // Use a data contract as illustrated in the sample below to add composite types to service operations.
    [DataContract]
    public class CompositeType
    {
        bool boolValue = true;
        string stringValue = "Hello ";

        [DataMember]
        public bool BoolValue
        {
            get { return boolValue; }
            set { boolValue = value; }
        }

        [DataMember]
        public string StringValue
        {
            get { return stringValue; }
            set { stringValue = value; }
        }
    }
}


The Service1.svc.cs file looks like bellow:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using System.ServiceModel;
using System.ServiceModel.Web;
using System.Text;

namespace MyService
{
    // NOTE: You can use the "Rename" command on the "Refactor" menu to change the class name "Service1" in code, svc and config file together.
    // NOTE: In order to launch WCF Test Client for testing this service, please select Service1.svc or Service1.svc.cs at the Solution Explorer and start debugging.
    public class Service1 : IService1
    {
        public string GetData(int value)
        {
            return string.Format("You entered: {0}", value);
        }

        public CompositeType GetDataUsingDataContract(CompositeType composite)
        {
            if (composite == null)
            {
                throw new ArgumentNullException("composite");
            }
            if (composite.BoolValue)
            {
                composite.StringValue += "Suffix";
            }
            return composite;
        }
    }
}

4. The service will look like bellow in browser.

Service in browser
Now please create one website to consume the Service. Now we have the website.
The next work is to add service reference for the service, which we have created above.

1. Right click on the Website and the add service reference. Bellow i have provided the screenshots, please have a look.

Add Service reference

3. A pop up will open there you can add your service reference URL and you can add your service there.

Service reference window

You can get the service reference url by viewing the service in browser. From the browser you can get the service url.

Service Reference link
You can change your reference name like bellow:

Reference Name

Now you are done with reference adding in website. Now you can call the service for the website. Bellow here is some code

using MyServiceReference;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;

public partial class User : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Service1Client client = new Service1Client();
        lblUserName.Text = client.GetData(4);
    }
}

This was small demo to Create and consume WCF service. Please put your valuable comments.

Select child checkboxes upon selection of parent checkbox

This section will give you a idea on bellow items

1.How to select a group of CheckBoxes at a time.
2.How to use prop method in Jquery.

Description:
On the Parent Check box click 2 things we need to do:
1. Need a selector which will get all the check boxes.
2. Need a Method which will append the checked property to the check boxes.

Note:
Please Copy all the bello Html codes into a Html file and open that file in one browser.
You will see one parent Check box and multiple check boxes.
Please select the parent check box all the Child items will be selected automatically.

Demonstration:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-1.11.0.js"></script>
    <script>
        $(document).ready(function () {
            //The click event will fire by selecting/de-Selecting the Parent CheckBox
            $('#chkSelectAll').click(function (e) {
                //prop method will Add the property to the elements
                //The prop methid will take 2 parameters one is the propertey Name. 2nd one is propertey value
                $('#chkNumber td input:checkbox').prop('checked', this.checked);
            });
        });
    </script>
</head>
<body>
    <div>
        <input type="checkbox" name="chkSelectAll" id="chkSelectAll">
        <label for="chkSelectAll">Select All</label>

        <table style="margin-left: 18px;" id="chkNumber">
            <tbody>
                <tr>
                    <td><input type="checkbox" value="1" name="chkNumber$0" id="chkNumber0"><label for="chkNumber0">One</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="2" name="chkNumber$1" id="chkNumber1"><label for="chkNumber1">Two</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="3" name="chkNumber$2" id="chkNumber2"><label for="chkNumber2">Three</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="4" name="chkNumber$3" id="chkNumber3"><label for="chkNumber3">Four</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="5" name="chkNumber$4" id="chkNumber4"><label for="chkNumber4">Five</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="6" name="chkNumber$5" id="chkNumber5"><label for="chkNumber5">Six</label></td>
                </tr>
                <tr>
                    <td><input type="checkbox" value="7" name="chkNumber$6" id="chkNumber6"><label for="chkNumber6">Seven</label></td>
                </tr>
            </tbody>
        </table>
    </div>
</body>
</html>

For your reference:
Please have a look on Jquery Prop Method

Showing Loading Image till the Page ready Using Jquery.

Complete Code here;

How it works:
In my page there are 2 divs
1. loading Image Div
2.Rest of the Page Content.

In the page it self the Loading image Div is visible and The Content Div is hidden.
Just we need to do 2 thing
1.Hide the Loading image Div
2.Unhide the Content Div

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <title></title>
    <script src="jquery-1.11.0.js"></script>
    <script type="text/javascript">
        window.onload = function () {
            $("#dvLoadingImage").fadeOut(100);
            $("#dvContent").fadeIn(100);
        };
    </script>
    <style>
        #dvLoadingImage {
            color: rgb(119, 69, 233);
            margin-left: 35%;
            margin-top: 13%;
        }
         #dvContent {
            font-size: 152px;
            margin-left: 20%;
            margin-right: 20%;
            display: none;
            background-image: url('Everest_North_Face_toward_Base_Camp_Tibet_Luca_Galuzzi_2006_edit_1.jpg');
        }
    </style>
</head>
<body>
    <div id="dvLoadingImage" >
        <img src="images.jpg" />
    </div>
    <div style="" id="dvContent">
        <span>Body Contents Goes here.</span>
    </div>
</body>
</html>