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: 212]

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


Share/Save/Bookmark Subscribe

Tags: , , , ,

ASP.NET | JQuery

Comments

12/6/2009 8:54:19 PM #

trackback

Using jqGrid with ASP.NET Web Forms - Part II

You've been kicked (a good thing) - Trackback from DotNetKicks.com

DotNetKicks.com

12/9/2009 3:31:07 AM #

pingback

Pingback from webmastercrap.com

Webmaster Crap  » Blog Archive   » Prabir's Blog | Using jqGrid with ASP.NET Web Forms - Part II

webmastercrap.com

12/9/2009 4:35:36 AM #

pingback

Pingback from scriptsrss.com

Prabir's Blog | Using jqGrid with ASP.NET Web Forms - Part II Scripts Rss

scriptsrss.com

12/14/2009 1:03:48 AM #

google adwords consultants

Do you accept guest posts? I would love to write couple articles here.
I was wondering what is up with that weird gravatar??? I know 5am is early and I'm not looking my best at that hour, but I hope I don't look like this! I might however make that face if I'm asked to do 100 pushups. lol

google adwords consultants United States

12/16/2009 5:30:00 AM #

Scented Candles Online

I have recently started using the blogengine.net and I having some problems here? in your blog you stated that we need to enable write permissions on the App_Data folder...unfortunately I don't understand how to enable it.

Scented Candles Online United States

12/16/2009 5:52:50 AM #

prabirshrestha

hi,
actually it is a personal blog, where i share my thoughts and ideas.
but accepting guest post doesn't seem tat bad at all though. quite a good idea.
we can try it though.
you can send me an email at here attaching the post in .doc format http://blog.prabir.me/contact.aspx

prabirshrestha Nepal

12/16/2009 5:57:17 AM #

prabirshrestha

By default in asp.net 2.0 App_Data already has write permissions, but other directories don't have. To enbale write permissions to the directory you need to use the hosting control pannel which they provide, such as cpanel or plesk.
Please refer to their respective documentation and help on enablining write permission.
I remeber writing on one of the post that we need to use. could you give send me the link to the post so that i can help u further.

prabirshrestha Nepal

12/16/2009 5:59:08 AM #

pingback

Pingback from neorack.com

Prabir's Blog | Using jqGrid with ASP.NET Web Forms – Part II | Neorack Tutorials

neorack.com

12/31/2009 3:00:33 PM #

trackback

Best of 2009

Best of 2009

Prabir's Blog

blog comments powered by Disqus