Tuesday, 5 May 2009

jqGrid with ASP .NET Web Forms

A quick write-up on my findings to use the amazing jqGrid v3.4.3 with ASP .NET 2.0 Web Forms. Surprisingly, there is no clear demo./website which enumerates on this usage. After some effort, got it finally working. Please note this is w.r.to ASP .NET 2.0 and I am just a day/two old with jqGrid!


(1) Suggested to not use PageMethods - can look at the "different" pains by different people at this link - http://www.west-wind.com/weblog/posts/152493.aspx.
If needed I can add mine into the list!


(2) The relevant partial code in the *.aspx file(without sending any parameters) is:

.......
.......
jQuery(document).ready(function() {
$('#list').jqGrid({
datatype: function() {
$.ajax({
url: "jqGrid.asmx/jQGridDataASMX",
data: "{}",
dataType: "json",
type: "POST",
contentType: "application/json; charset=utf-8",
complete: function(jsondata, stat) {
window.alert("Status received is " + stat);
window.alert("Response text is: " + jsondata.responseText);
if (stat == "success") {
var thegrid = jQuery("#list")[0];
thegrid.addJSONData(eval("(" + jsondata.responseText + ")"));
}
}
});
},
colNames: ['Col1', 'Col2', 'Col3'],
colModel: [
{ name: 'Col1', index: 'Col1', width: 40, align: 'left' },
{ name: 'Col2', index: 'Col2', width: 40, align: 'left' },
{ name: 'Col3', index: 'col3', width: 200, align: 'left'}],
pager: jQuery('#pager'),
rowNum: 10,
rowList: [10, 20, 30],
viewrecords: true,
imgpath: 'jqGrid-3.4.3/themes/basic/images',
caption: 'jqGrid NewComer - First Grid'
});
});


........
........






When sending parameters to the web service method use the JSON object which is defined in "json2.js"(You can download from - http://www.JSON.org/json2.js).
Eg. var jsonStr = JSON.stringify(data);
and then place the jsonStr variable within the "data" parameter of the $.ajax request like:
url: "jqGrid.asmx/jQGridDataASMX",
data: jsonStr,
dataType: "json",


(3) The complete jqGrid.asmx file is:

using System;
using System.Collections.Generic;
using System.Web;
using System.Web.Services;
using System.Web.Script.Services;
using System.Web.Script.Serialization;

public class RowElement
{
public string id;
public string[] cell;
}

public class MainGrid
{
public string total;
public string page;
public string records;
public RowElement[] rows;
}


///

/// Summary description for jqGrid
///

[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[ScriptService]
public class jqGrid : System.Web.Services.WebService {

[WebMethod]
public MainGrid jQGridDataASMX()
{
/* {
total: 'xxx',
page: 'yyy',
records: 'zzz',
rows : [
{id:'1', cell:['cell11', 'cell12', 'cell13']},
{id:'2', cell:['cell21', 'cell22', 'cell23']}
]
} */

MainGrid mg = new MainGrid();
mg.total = "1";
mg.page = "1";
mg.records = "1";

mg.rows = new RowElement[1];
mg.rows[0] = new RowElement();
mg.rows[0].id = "1";
mg.rows[0].cell = new string[3];
mg.rows[0].cell[0] = "cell1";
mg.rows[0].cell[1] = "cell2";
mg.rows[0].cell[2] = "cell3";

return mg;
}

}


(5) The resultant output is:


















Hope this helps for someone to get a heads-up with jqGrid and ASP .NET 2.0!


Also check-out a very good site on the jQGrid with ASP .NET using HTTP handlers - http://geeks.netindonesia.net/blogs/cipto/archive/2009/04/03/jqgrid.aspx


40 comments:

Achutha Krishnan said...

Thanks for the article. Can you upload a sample of which you made jQGrid with ASP.NET?

Praveen said...

You can pick the Visual Studio 2008 solution from below:

http://sites.google.com/site/praveen1305now/documents/jqGridWebMethods.zip?attredirects=0

Hope this helps! Also, to note this is just a very very basic grid and you can do lots, lots and lots more with it. The post was just to get some "confidence" going with ASP .NET, since there was n't any available when I started looking out.
Have a look at the link to use the grid via ASP .NET handlers, which I have posted. Personally, I found ASHX is quite flexible than web methods. I could be wrong if you can find some innovative ways to do!

-Praveen

Achutha Krishnan said...

Thanks for a good sample. I'm novice to jqGrid. Will try more samples and let you know. Can we pass dataset to the table as you pass the cells from asmx file?

Praveen said...

Nope. You need to convert the dataset to XML or JSON. I would prefer later because it is lighter in weight than XML.
I believe a Google should get you some methods to convert a datatable to JSON.
Atleast I got one immediate -
http://weblogs.asp.net/navaidakhtar/archive/2008/07/08/converting-data-table-dataset-into-json-string.aspx

Hope this helps!

Achutha Krishnan said...

Thanks Praveen. I managed to bring a jQuery Grid in asp.net. I tried to convert the Datatable to JSON string, but didn't get the exact one. I used other method and made it working. Now I'm not able to Sort the Grid. Should I use any plugin for Soring. My code is like:

pager: jQuery('#pager'),
rowNum: 5,
rowList: [10, 20, 30],
sortname: 'Name',
sortorder:'desc',
viewrecords: true,
imgpath: 'jqGrid-3.4.3/themes/coffee/images',
caption: 'jqGrid First Grid',
width: 300

Initially, it is not sorting. Clicking on the Column's header is also not sorting. Any idea?

Praveen said...

You need to implement sorting at the back-end.
Whenever you click the header of the table(i.e. the column), a request is sent to the back-end to redraw the grid for the current grid, along with the column one is trying to sort and the order of sorting, i.e. "desc" or "asc" (within the "sortorder" variable). All these info. is being sent back to the server.
To see what I am saying, please use a tool called "Fiddler" to monitor the web request/response. It will take you a long way in debugging and understanding how things work.
Also, since you have got the feel of how things work, I would suggest to start using ASP .NET handlers as in this link:
http://geeks.netindonesia.net/blogs/cipto/archive/2009/04/03/jqgrid.aspx
along with JSON data.
With ASHX files, you have plenty of flexibility, which is very much needed in doing other operations with the grid.

Hope this helps.

-Praveen

Praveen said...

a request is sent to the back-end to redraw the grid for the current grid

SHOULD READ AS: a request is sent to the back-end to redraw the grid for the current page

Achutha Krishnan said...

Ok Praveen. But I've to learn using ashx. I'll do that. Have you done any small sample using ashx? (Not jQuery necessarily).

Praveen said...

ASHX is very simple. Nothing really to learn. It is just that you need to write back content to the browser from the ASHX file, here it is JSON data. ASPX file does it as HTML by default. Have a look at the solution I gave across. It has some comments on JSON serialization.
Yes, done a great amount in ASHX, but unfortunately they are configured with Oracle DB connections. So nothing would make sense to yourself unless otherwise you have the same Oracle schema at your end.
The earlier link (*geeks*indonesia), I had said is of great use, which is where I started from, reg. jQGrid. Give a try for "few" days and if things don't move forward, post your code and we could have a look at it!
Ofcourse there are plenty of links on the net on using ASHX. I learnt it just for jQGrid and found it exciting!

All the best!

-Praveen

Achutha Krishnan said...

Yeah Praveen, we made it. I had a look at the link which you gave and managed to Sort, Add, Delete, Edit and Update the records. It is really amazing. Is it fine converting the data to XML and pushing to the front? Will JSON be faster than XML?

Praveen said...

Good to know on your progress!
I would prefer JSON because of its comparable lightweight than XML.

-Praveen

Achutha Krishnan said...

Will try in JSON and let you know. Tried once and didn't get. You use ashx to convert to JSON?

Praveen said...

Yes, I use ASHX only. Once you have created the "grid" object in your *.ashx file, use the below code:

JavaScriptSerializer js = new JavaScriptSerializer();
string content = js.Serialize(grid);
context.Response.ContentType = "application/json; charset=utf-8";

context.Response.Write(content);
context.Response.End();


Also, ensure that you include "System.Web.Script.Serialization" namespace which is part of the ASP .NET AJAX.


Hope the above helps!

Achutha Krishnan said...

Serializing the DataTable does not bind to the jqGrid. The status is "Success". but it won't bind. Can you reply to my email akbathey at gmail dot com?

Anita said...

I am getting following error -
Microsoft JScript runtime error: '$.jgrid.defaults' is null or not an object

How to resolve this one?

Anita said...

I am getting following error -
Microsoft JScript runtime error: '$.jgrid.defaults' is null or not an object

How to resolve this one?

Praveen said...

Few things to check:
(1) Can you run jQuery as such, i.e. no jqGrid etc. If yes then,
(2) If you are the jqGrid code-base, ensure that the variable "pathtojsfiles" in "jquery.jqGrid.js" is pointing to the right location.

Hope the above helps.

-Praveen

Hugo S said...

Hi.. first sorry for my english.. but i have a question.. when execute my document.ready, i displayed my jqGrid and it's block my page with a modal.. hope help me.. thanks!!

Praveen said...

What version of jQGrid are you using? Does it happen in all browsers, i.e. Internet Explorer, FireFox? Can you show me a screen-shot of the browser?

Hugo S said...

thanks for you help..
and No, it's occurs only in firefos 3,(works better in ie 6)
the jqGrid version it's
/*
* jqGrid 3.5-beta - jQuery Grid
* Copyright (c) 2008, Tony Tomov, tony@trirand.com
* Dual licensed under the MIT and GPL licenses
* http://www.opensource.org/licenses/mit-license.php
* http://www.gnu.org/licenses/gpl.html
* Date:2009-05-24 build 10
*/

I will send you a screenshot in your mail..

Hugo S said...

http://hsendoa.blogspot.com/

praveen this is the screenshot

Chass said...

THANK 4 four help but, I find the error..
I not import the css from jqgrid..

Achutha Krishnan said...

Praveen,

Instead of using WebService to call the method, have you used C# Code-Behind to call the Method?

LonelyRonaldinho said...

hi, actually, this is not a comment.
it is a question.
can you please kindly help me?

I have downloaded you vs2008 project and deployed to IIS 5.1.

I have modified jquery code.
just set editurl.

editurl: "jqGrid.asmx/EditGridDataASMX"

and created a function EditGridDataASMX

however, when I run the web app.
the edit the content using "form editing".
when I click the "submit" button on the form.
the internal server error 500 occurs.

is it from the configuration on IIS?

or other issues ?

thank you very much!!

Praveen said...

Internal Server 500 means that the web-page request has failed.
The reason could be that the file does n't exist or the file which you are running is having compilation errors etc...
Posting the code will help to identify the issue.

-Praveen

Mohamad Kaifi said...

Hi praveen,
great post dear :),

but i have an issue when i am using this method of binding the grid..then its not giving any error but data is not displayed in the grid..

i m using jqGrid 3.5 with asp.net 3.5..

what may be the reason...plz help me..i m fighting with this for last 3-4 days :(..

thanks..plz reply asap...

Mohamad Kaifi said...

if u want..i can send u the whole code..but please try to find it praveen..

Praveen said...

Get me the code and will have a look at it....

Mohamad Kaifi said...

pravin please send me your mail id on mohamadkaifi@gmail.com..so that i can send u the code....

Kevin said...

Actually we (Trirand - the guys behind jqGrid), decided to create a brand new site dedicated on ASP.NET WebForms & MVC and how to use it with jqGrid.

We will create a set of examples (and in the case of ASP.NET Webforms, a standalone grid component, with design-time support, binding to all datasources, automatic handling of sorting, paging, filtering, etc).

First examples can be found here:
http://trirand.net/

and the source code here:

Achutha Krishnan said...

@Kevin,

Super thanks man. That was a good link.

Mike Anderson said...

@Kevin,

Great to see some examples with ASP.NET. These will be super helpful. Where can we find the server control that is referenced in the examples?

Achutha Krishnan said...

@Mike

I was about to ask the same question.

@Kevin

I believe that site is not fully demonstrating. Where can we find the server control?

David said...

To make this work with ASP.NET 3.5 or 4.0beta you need to make a small change to 'unwrap the d' introduced in the ASP.NET AJAX 3.5 implementation.

change
thegrid.addJSONData(eval("(" + jsondata.responseText + ")"));


to
thegrid.addJSONData(eval("(" + jsondata.responseText + ").d"));

David said...

To fix the '$.jgrid.defaults' error you need to reference the grid.locale-??.js language file *before* the jquery.jqGrid.min.js file.

Sorry, can't post the example code (not allowed), you'll have to work it out.

Pedro Martins said...

Great Help, Praveen!

Thanks mate

रुपेश कुमार तिवारी said...

Hi how to show the loading message while loading the jqGrid. I have one button on click of that button i am calling $("#grid").jqGrid({..})

But on first click it is calling webservice method while on 2nd click it does not call the webservice method at all.

Anand G said...

Nice article.

I need a wrapper (.NET Manager wrapper) class for trirand.jqgrid is it available?

Please support

Atul Savaliya said...

Here is complete working code of jqgrid with asp.net. you can download from here :
http://oceancloudy.com/blog/jqgrid-with-asp-net-in-csharp/

Zoebali Maknojia said...

Hi Praveen.I have followed the article http://geeks.netindonesia.net/blogs/cipto/archive/2009/04/03/jqgrid.aspx
but unfortunately I can't see any data in JQGRid,can you please help me.