Prabir's Blog

where the tech matters...

Using jqGrid with ASP.NET Web Forms - Part II

December 06
by prabir 6. December 2009 19:43

This article is continuation of my previous article.

To start of with, we first need to create an asmx web service in JSON format. If you are not sure of how to use JSON in asmx web services, I would suggest you to read my previous articles - JSON in Classical Web Services - ASMX and Consuming ASP.NET Web Services using JQuery.

Lets create a web service method called GetListOfPersons. Remember to decorate it with ScriptMethod Attribute as our means of data communication will be in JSON format. In the following example JsonHelper.GetPersons() is responsible for retrieving the list of persons. You can have a appropriate data access logic out there.

[WebMethod]
[ScriptMethod]
public string GetListOfPersons()
{
    List<Person> persons = JsonHelper.GetPersons();
    return Newtonsoft.Json.JsonConvert.SerializeObject(
        new PagedList(persons, persons.Count, 1, persons.Count));
}

Then we create a new instance of PagedList object that we defined in the previous post. Here’s one of the constructor that we will be using in case you have forgotten.

public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize);

For simplicity we will not be including features such as paging and sorting for now. (I will include it in later posts.) So, here the rows will be the list of persons retrieved, totalRecords will be the number of persons in the list hence persons.Count, pageIndex will just be simple as 1 as all data will be displayed on the same page number 1. pageSize will be the totalRecords as we don’t want to having paging enabled for now.

Now that the instance of PageList has been created. We need to serialize the object into JSON format which can be recognized easily by jqGrid. To achieve this we make use of Newtonsoft.JSON library by calling the SerializeObject method as shown above.

Now that we are done with the web service, we need to start coding the user interface in HTML and JavaScript.

Create a HTML table along with an ID. This table will be rendered as jqGrid when previewed in the browser.

 

<table id="table" cellpadding="0" cellspacing="0">
</table>

 

Include appropriate css style sheets and javascript files required for jqGrid to function. You will need the JQuery UI,  and multiselect also. Multiselect JQuery plugin can be obtained from http://quasipartikel.at/multiselect.

 

<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-1.3.2.min.js") %>"></script>
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/redmond/jquery-ui-1.7.2.custom.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.jqgrid.css") %>" />
<link type="text/css" rel="stylesheet" href="<%= ResolveClientUrl("~/styles/ui.multiselect.css") %>" />
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery-ui-1.7.2.custom.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/i18n/grid.locale-en.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/jquery.jqGrid.min.js") %>"></script>
<script type="text/javascript" src="<%= ResolveClientUrl("~/scripts/ui.multiselect.js") %>"></script>

 

Let me write the code first and then explain later on. So it would be easier for you guys to copy paste and learn.

 

<script type="text/javascript">
    $(function () {
        $("#table").jqGrid({
            datatype: function (pdata) { getData(pdata); },
            height: 250,
            colNames: ['ID', 'First Name', 'Last Name'],
            colModel: [
           		{ name: 'ID', width: 60, sortable: false },
           		{ name: 'FirstName', width: 200, sortable: false },
           		{ name: 'LastName', width: 200, sortable: false }
           	],
            imgpath: '<%= ResolveClientUrl("~/styles/redmon/images") %>',
            caption: "Sample JSON data retrieved from ASMX web services"
        });
    });
    function getData(pData) {
        $.ajax({
            type: 'POST',
            contentType: "application/json; charset=utf-8",
            url: '<%= ResolveClientUrl("~/WebService.asmx/GetListOfPersons") %>',
            data: '{}',
            dataType: "json",
            success: function (data, textStatus) {
                if (textStatus == "success")
                    ReceivedClientData(JSON.parse(getMain(data)).rows);
            },
            error: function (data, textStatus) {
                alert('An error has occured retrieving data!');
            }
        });
    }
    function ReceivedClientData(data) {
        var thegrid = $("#table");
        thegrid.clearGridData();
        for (var i = 0; i < data.length; i++)
            thegrid.addRowData(i + 1, data[i]);
    }
    function getMain(dObj) {
        if (dObj.hasOwnProperty('d'))
            return dObj.d;
        else
            return dObj;
    }
</script>

 

jQuery ready function initializes the jqGrid. The data type we have chosen is a custom function with a parameter called pdata. pdata is a short of ParameterData. You can name it what ever you feel comfortable with. It then calls the function called getData. ColName is an array of string containing the column header. ColModal contains more information on how to render data.

Note: The name in ColModal is not the same as ColName but rather its same as that of the list of objects, which was passed as enumerable rows when creating PageList.

Function getData is responsible for doing an AJAX request to the webservice. If success it calls another function called ReceivedClientData. RetrieveClientData function is responsible for appending the data to the grid.

As the data is Ajax request and our response is in string, we need to parse the JSON string to JSON object using json2.js. (We will not be using eval due to security reasons though it is possible.)

GetMain function is used to trip of the “d” property, which is generated by web services if using new versions of ASP.NET for security reasons.

jqGridAspNetWebForms.zip (617.09 kb) [Downloads: 766]

jquery.jqGrid-3.6.zip (274.12 kb) [Downloads: 744]
jquery-ui-1.7.2.custom.zip (745.92 kb) [Downloads: 352]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , , , ,

ASP.NET | JQuery

Using jqGrid with ASP.NET Web Forms - Part I

November 14
by prabir 14. November 2009 14:55

(As this article grew up to be quite long then I expected, I have broken up this post into different Parts.)

When I first started to use jqGrid few months back, I couldn’t find good tutorials on using jqGrid with ASP.NET webforms. Any search on ASP.NET and jqGrid would lead to ASP.NET MVC tutorial. So, I thought of writing this article to help you guys.

I will be using jqGrid version 3.6 (the codes presented here will most probably work with the earlier versions too – You can download the latest version of jqGrid from http://www.trirand.com/blog or version 3.6 at the end of this article).

We will be using JSON as means of data communication which will be provided by asmx web services. If you don’t know how to use JSON in asmx web services, I would suggest you to read my previous articles - JSON in Classical Web Services - ASMX and Consuming ASP.NET Web Services using JQuery. (Similar concepts can also be applied to WCF RESTful web services.)

How does jqGrid understand our JSON format?

Answering the above question is vital for getting things done right. So lets start with understanding JSON format used by jqGrid.

{
    "page":"1",
    "total":4,
    "records":"10",
    "rows":[
        {"id":"1","cell":["Prabir","Shrestha"]},
        {"id":"2","cell":["Bill","Gates"]},
        {"id":"3","cell":["Steve","Ballmer"]}
    ]
}

Page stands for the current page index. Total represents the total number of pages available and records for the total number records in the entire data list including those not shown in the rows.

Let’s have a closer look at rows. It contains 2 fields, id and cell. The cell contains the main data which needs to be rendered. Here again we have two fields. Try guessing what those fields are.

The first field represents First Name and second field represents Last Name. It is basically an array of string. If others are consuming your web services it would be very difficult for them to actually guess the meaning of these fields. To overcome this difficulty in understanding, lets take an alternative approach. We would then have the result in the following manner.

{
    "page":"1",
    "total":4,
    "records":"10",
    "rows":[
        {id:1,FirstName:"Prabir",LastName:"Shrestha"},
        {id:1,FirstName:"Bill",LastName:"Gates"},
        {id:1,FirstName:"Steve",LastName:"Ballmer"},
    ]
}

The above example is more descriptive and easier to understand. But now another problem arises. How do I convert to that JSON format?

To work with this we create a helper class called PagedList as follows.

using System;
using System.Collections;

public class PagedList
{
    IEnumerable _rows;
    int _totalRecords;
    int _pageIndex;
    int _pageSize;
    object _userData;

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize, object userData)
    {
        _rows = rows;
        _totalRecords = totalRecords;
        _pageIndex = pageIndex;
        _pageSize = pageSize;
        _userData = userData;
    }

    public PagedList(IEnumerable rows, int totalRecords, int pageIndex, int pageSize)
        : this(rows, totalRecords, pageIndex, pageSize, null)
    {
    }

    public int total { get { return (int)Math.Ceiling((decimal)_totalRecords / (decimal)_pageSize); } }

    public int page { get { return _pageIndex; } }

    public int records { get { return _totalRecords; } }

    public IEnumerable rows { get { return _rows; } }

    public object userData { get { return _userData; } }

    public override string ToString()
    {
        return Newtonsoft.Json.JsonConvert.SerializeObject(this);
    }
}

Notice that I have included all the fields required by jqGrid. And all these also violates standard C# naming standards. This is to make it easy (Javascript is case sensitive) for us to serialize the object to JSON string understandable by  jqGrid by using the help of Newtonsoft JSON library. Total is also calculated automatically for us.

The rows is basically IEnumerable, which means we can also assign List<T> to it. Which makes our work easier. And since we have overridden the ToString method, converting the object to JSON string representation is far lot easier.

Then how do I put all the things together?

For example lets assume the Person class is declared as below.

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
}

and let us also assume that there is a method called GetPersons which returns us a List of Person (List<Person>).

Now to create the PagedList, we simply call the constructor of the PagedList.

PagedList pagedList = new PagedList(GetPersons(), 10, 1, 3);

It will then create a new instance of PagedList and assign the GetPersons List<Person> to rows, 10 to records, 1 to page index and 3 to pageSize.

There is no default constructor for PagedList and it is also an immutable object, which means if you need to change anything you will need to create a new instance of it again. The reason I did this was because, I always used to get confused between total, page and records. So I came up with a solution that I would always use constructor and the parameters in these constructors would be name is such a way that it would not confuse me, so I landed up naming them as pageIndex, pageSize and so on. The other way around would be to use the get and set for all the properties and use the xml documentation features using /// <summary> to prevent the confusion.

This concludes the Part I for Using jqGrid with ASP.NET web forms. In part II, I will be going through on how to actually display it in jqGrid. Stay tuned.

jquery.jqGrid-3.6.zip (274.12 kb) [Downloads: 744]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , , ,

ASP.NET | JQuery

Consuming ASP.NET Web Services using JQuery

November 10
by prabir 10. November 2009 19:49

In this tutorial we will be using JQuery to consume Asp.Net web services.

If you do not know how to create webservices that output JSON results please see my previous blog post on JSON in Classical Web Services ASMX.

If you have reached this point, I assume you know how to create webservices in JSON.

Inorder to do this, we will be using JQuery’s. $.ajax. As asp.net explicitly makes all ScriptMethods POST, we cannot use JQuery’s get method.

contentType needs to be changed to application/json and dataType as json.

data:’{}’ is the parameter being passed.

success:function(msg){} this method is executed when the POST successfully happens, and stores the result in msg.

error:function(){} this method is executed when an error occurs.

$.ajax({
    type: 'POST',
    url: '<%= ResolveClientUrl("~/JsonWebService.asmx/ReturnStudent") %>',
    contentType: 'application/json; charset=utf-8',
    dataType: 'json',
    data: '{}',
    success: function (msg) {
        var jsonObject = JSON.parse(getMain(msg));
        alert('FirstName:' + jsonObject.FirstName);
    },
    error: function () {
        alert('error occured');
    }
});

ReturnStudent is a WebService Method which is shown as below.

[WebMethod]
[ScriptMethod]
public string ReturnStudent()
{
    return JsonHelper.ToJson(JsonHelper.CreateSampleStudent());
}

The above method create an Object and then serializes to JSON string and returns the JSON string as the output.  (You can read more on this at http://blog.prabir.me/post/JSON-in-Classical-Web-Services-ASMX.aspx – The same example is used. I’m using Newtonsoft’s JSON library to convert the object to JSON string).

When we execute the above JQuery code, msg contains the JSON string not a JSON object. (Our WebMethod returns a string.) So we need to parse the JSON string to a JSON object. To do this we will be using a 3rd party library called json2.js. You can read more about parsing at http://blog.prabir.me/post/Parsing-JSON-in-JavaScript.aspx. To achieve this we use JSON.parse(msg). But we need to be a bit careful out here. .NET 2.0 and .NET 3.5 will give different output. .NET 3.5 adds the d property which we have to be careful. The result would be as follows.

var net20ResultFromWebService = "{\"FirstName\":\"Prabir\",\"LastName\":\"Shrestha\"}";
var net35ResultFromWebService = { "d": "{\"FirstName\":\"Prabir\",\"LastName\":\"Shrestha\"}" };

Notice the “d”. It was added for security reasons.

So, instead of just using JSON.parse(msg) we use our own custom helper function called getMain(). It basically strips off the “d” property if it contains else returns the object it self. This is important especially if you are consuming others webservices and all of the sudden when they upgrade the .NET version, all you site cracks down. Taking this extra precaution might be a bonus to you.

Here’s the function that solves the .NET version compatibility problem.

function getMain(dObj) {
    if (dObj.hasOwnProperty('d'))
        return dObj.d;
    else
        return dObj;
}

What if you have a function which contains parameters like below.

[WebMethod]
[ScriptMethod]
public string Print(string name, int times)
{
    // code omitted for brevity
}

Remember the data:’{}’ parameter in $.ajax I told before. We need to make use of it.

data: "{name:'Prabir',times:2}"

It would be represented as above in JSON string format. That is it.

In the upcoming posts I will be guiding through on how increase the user experience by showing animating features (loading…please wait…). Stay tuned.

JQueryAndAspNetWebservices.zip (769.57 kb) [Downloads: 472]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags:

JQuery

Load JQuery from Google

August 16
by prabir 16. August 2009 11:34

Due to JQuery’s huge popularity, many of the websites have been using JQuery. To decrease the bandwidth to and get faster download performance, it would be better to load from a general website such as Google. If other websites have downloaded it from Google, then the browser can serve from the local cache.

In this tutorial we will be using Google to load JQuery.

This can be achieved by adding a reference to JQuery url from Google.

<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.min.js"></script>

Or it could be achieved by using Google AJAX Libraries API.

<script type="text/javascript" src="http://www.google.com/jsapi"></script>
<script type="text/javascript">
	google.load('jquery','1.3.2');
</script>

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: ,

JQuery

Get Intellisense support for JQuery in VS

July 25
by prabir 25. July 2009 17:27

JQuery intellisense has been around for quite a long time. And the great news is that it is officially supported by Microsoft. Its a lightweight JavaScript framework having huger users.

Installing Intellisense support:

  1. Make sure you are running the Service Pack 1 of Visual Studio installed. You can download it from here.
  2. Then download the JScript editor support for “-vsdoc.js” patch (KB958502) at the end of this post or from MSDN.
  3. Then go to the official JQuery download page at http://docs.jquery.com/Downloading_jQuery#Download_jQuery.

imageSelect the Visual Studio documentation when downloading.

Then reference the JavaScript file you just downloaded

<script type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js"></script>

 

Now you must be getting the intellisense support in your visual studio. Pages that inherits from master page will get the intellisense support, But the user controls will not be getting the intellisense support. To do that you can use the following hack.

<% if (false){ %>
        <script type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js"></script>
<% } %>

The expression will always evaluate to false. That means *-vsdoc2.js file will never be added to the webpage. But the visual studio will evaluate it and provide the intellisense support.

image

The way I use JQuery:

Since the *-vsdoc2.js file is quite huge I prefer to use .min.js version of JQuery. I reference it by using the following way.

<script type="text/javascript" src='<%= ResolveClientUrl("~/js/jquery-1.3.2.min.js") %>'></script>
<% if (false){ %>
     <script type="text/javascript" src="js/jquery-1.3.2-vsdoc2.js"></script>
<% } %>

Notice the ResolveClientUrl. Its helpful when your page inherits from the master page and the page lies in different folder.

Another way is rather just reference .min.js file and add the following line at the top of the file.

/// <reference path="jquery-1.3.2-vsdoc.js" />

This allows the Visual Studio to automatically recognize the file and provide appropriate intellisense support.

VS90SP1-KB958502-x86.exe (JSEditor Patch) (2.13 mb) [Downloads: 741]
jquery-1.3.2-all.zip (95.67 kb) [Downloads: 662]

If you enjoyed this post, make sure you subscribe to my RSS feed!

Tags: , ,

JQuery