Using jQuery Grid With ASP.NET MVC

Continuing in my pseudo-series of posts based on my ASP.NET MVC Ninjas on Fire Black Belt Tips Presentation at Mix (go watch it!), this post covers a demo I did not show because I ran out of time. It was a demo I held in my back pocket just in case I went too fast and needed one more demo.

A common scenario when building web user interfaces is providing a pageable and sortable grid of data. Even better if it uses AJAX to make it more responsive and snazzy. Since ASP.NET MVC includes jQuery, I figured it’d be fun to use a jQuery plugin for this demo, so I chose jQuery Grid.

After creating a standard ASP.NET MVC project, the first step was to download the plugin and to unzip the contents to my scripts directory per the Installation instructions.

jquery-grid-scripts

For the purposes of this demo, I’ll just implement this using the Index controller action and view within the HomeController.

With the scripts in place, go to the Index view and add the proper call to initialize the jQuery grid. There are three parts to this:

First, make sure to add the required script and CSS declarations.

<link rel="stylesheet" type="text/css" href="/scripts/themes/coffee/grid.css" 
  title="coffee" media="screen" />
<script src="/Scripts/jquery-1.3.2.js" type="text/javascript"></script>
<script src="/Scripts/jquery.jqGrid.js" type="text/javascript"></script>
<script src="/Scripts/js/jqModal.js" type="text/javascript"></script>
<script src="/Scripts/js/jqDnR.js" type="text/javascript"></script>

Notice that the first line contains a reference to the “coffee” CSS file. There are multiple themes included and when you choose a theme, you need to be sure to include the theme’s CSS file. I chose coffee, because I drink a lot of it.

The Second step is to initialize the grid with a bit of JavaScript. This looks a bit funky if you’re not used to jQuery, but I assure you, it’s pretty straightforward.

<script type="text/javascript">
    jQuery(document).ready(function(){ 
      jQuery("#list").jqGrid({
        url:'/Home/GridData/',
        datatype: 'json',
        mtype: 'GET',
        colNames:['Id','Votes','Title'],
        colModel :[
          {name:'Id', index:'Id', width:40, align:'left' },
          {name:'Votes', index:'Votes', width:40, align:'left' },
          {name:'Title', index:'Title', width:200, align:'left'}],
        pager: jQuery('#pager'),
        rowNum:10,
        rowList:[5,10,20,50],
        sortname: 'Id',
        sortorder: "desc",
        viewrecords: true,
        imgpath: '/scripts/themes/coffee/images',
        caption: 'My first grid'
      }); 
    }); 
</script>

There are a few things you’ll have to be sure to configure here. First is the url property which points to the URL that will provide the JSON data. Notice that the value is /Home/GridData which means we’ll be implementing an action method named GridData soon. During the course of this post, we’ll change that property to point to different action methods.

The colNames property contains the display names for each column separated by columns. Ideally it should match up with the items in the colModel property.

The colModel property is an array that is used to configure each column of the grid, allowing you to specify the width, alignment, and sortability of a column. The index property of a column is an important one as that is the value that is sent to the server when sorting on a column.

See the documentation for more details on the HTML and JavaScript used to configure the grid.

The Third step is to add a bit of HTML to the page which will house the grid.

<h2>My Grid Data</h2>
<table id="list" class="scroll" cellpadding="0" cellspacing="0"></table>
<div id="pager" class="scroll" style="text-align:center;"></div>

With this in place, it’s time to implement the GridData action method to return the JSON in the proper format.

But first, let’s take a look at the JSON format expected by the grid. From the documentation, you can see it will look something like:

{ 
  total: "xxx", 
  page: "yyy", 
  records: "zzz",
  rows : [
    {id:"1", cell:["cell11", "cell12", "cell13"]},
    {id:"2", cell:["cell21", "cell22", "cell23"]},
      ...
  ]
}

The documentation I linked to also provides some gnarly looking PHP code you can use to generate the JSON data. Fortunately, you won’t have to deal with that. By using the Json helper method with an anonymous object, we can write some relatively clean looking code which looks almost just like the spec. Here’s my first cut of the action method, just to get it to display some fake data.

public ActionResult GridData(string sidx, string sord, int page, int rows) {
  var jsonData = new {
    total = 1, // we'll implement later 
    page = page,
    records = 3, // implement later 
    rows = new[]{
      new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
      new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?"}},
      new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?"}}
    }
  };
  return Json(jsonData);
}

A couple of things to point out. The arguments to the action methods are named according to the query string parameter names that jQuery grid sends via the Ajax request. I didn’t choose those names.

By naming the arguments to the action method exactly the same as what is in the query string, we have a very convenient way to retrieve these values. Remember, arguments passed to an action method should be treated with care. Never trust user input!

In this example, we statically create some JSON data and use the Json helper method to return the data back to the grid and Voila! It works!

jquery-grid-demo

Yeah, this is great for a simple demo, but I use a real database to store my data! Understood. It’s time to hook this up to a real database. As you might guess, I’ll use the HaackOverflow database for this demo as well as LinqToSql.

I’ll assume you know how to add a database and create a LinqToSql model already. If not, look at the source code I’ve included. Once you’ve done that, it’s pretty easy to transformat the data we get back into the proper JSON format.

public ActionResult LinqGridData
(string sidx, string sord, int page, int rows) { varnew HaackOverflowDataContext(); var jsonData = new { total = 1, //todo: calculate page = page, records = context.Questions.Count(), rows = ( from question in context.Questions select new { i = question.Id, cell = new string[] { question.Id.ToString(), question.Votes.ToString(), question.Title } }).ToArray() }; return Json(jsonData); }

Note that the method is a tiny bit busier, but it follows the same basic structure as the JSON data. After changing the JavaScript code in the view to point to this action instead of the other, we can now see the first ten records from the database in the grid.

But we’re not done yet. At this point, we want to implement paging and sorting. Paging is pretty easy, but sorting is a bit tricky. After all, what we get passed into the action method is the name of the sort column. At that point, we want to dynamically create a LINQ expression that sorts by that column.

One easy way to do this is to use the Dynamic Linq Query library which ScottGu wrote about a while back. This library adds extension methods which make it easy to create more dynamic Linq queries based on strings. Of course, with great power comes great responsibility. Make sure to validate the strings before you pass them into the methods. With this in place, we rewrite the action method to be (warning, DEMO CODE AHEAD!):

public ActionResult DynamicGridData
    (string sidx, string sord, int page, int rows) {
  var context = new HaackOverflowDataContext();
  int pageIndex = Convert.ToInt32(page) - 1;
  int pageSize = rows;
  int totalRecords = context.Questions.Count();
  int totalPages = (int)Math.Ceiling((float)totalRecords / (float)pageSize);

  var questions = context.Questions
    .OrderBy(sidx + " " + sord)
    .Skip(pageIndex * pageSize)
    .Take(pageSize);

  var jsonData = new {
    total = totalPages,
    page = page,
    records = totalRecords,
    rows = (
      from question in questions
      select new {
        i = question.Id,
        cell = new string[] {
          question.Id.ToString(), question.Votes.ToString(), question.Title 
        }
    }).ToArray()
  };
  return Json(jsonData);
}

Some things to note: The first part of this method does some initial calculations to figure out the number of pages we’re dealing with based on the page size (passed in) and the total record count.

Then given that info, we use the Dynamic Linq extension methods to do the actual paging and sorting via the line:

var questions = context.Questions.OrderBy(…).Skip(…).Take(…);

Once we have that, we can simply transform that into the array that jQuery grid expects and place that in the larger JSON payload represented by the jsonData variable.

With all this in place, you now have a pretty snazzy approach to paging and sorting data using AJAX. Now go forth and wow your customers. ;)

And before I forget, here’s the sample project that uses all three approaches.

What others have said

Requesting Gravatar... Jarrett Apr 14, 2009 4:42 PM
# re: Using jQuery Grid With ASP.NET MVC
This. Rocks. Much love for MVC and all who do such great work with it.
Requesting Gravatar... Mike Enriquez Apr 14, 2009 5:25 PM
# re: Using jQuery Grid With ASP.NET MVC
Thanks for the article. I've been fighting with an app (ASP.NET with Infragistics grids) that requires the same functionality.

Need to convince the boss to move to this... I can't wrap my head around the Postback model :(
Requesting Gravatar... lizai Apr 14, 2009 6:24 PM
# re: Using jQuery Grid With ASP.NET MVC
its so great! Thanks Phil!
Requesting Gravatar... Mohammad Azam Apr 14, 2009 7:46 PM
# re: Using jQuery Grid With ASP.NET MVC
Hi Phil,

Awesome post! I am really glad that JQuery includes a Grid control or else we will have to run loops and create tables. I am wondering that if third party tool vendors will start creating MVC controls.
Requesting Gravatar... Barranger Apr 14, 2009 8:12 PM
# re: Using jQuery Grid With ASP.NET MVC
Any chance of getting a snippet of adding the edit and delete links?
Requesting Gravatar... condition Apr 14, 2009 8:45 PM
# re: Using jQuery Grid With ASP.NET MVC
i want to add condition in query.
how to do it?
Requesting Gravatar... born2code Apr 14, 2009 8:56 PM
# re: Using jQuery Grid With ASP.NET MVC
cool. I am using the exact same thing, using jqGrid and MVC, in a production app except I use MySQL as the back end. I use a stored procedure to retrieve the data and then a little helper to convert the DataRows to json.
There is no real good way to use LINQ with MySQL while using stored procedures, so i had to roll out my own "poor man's ORM".

I have a question about the Skip() and Take(). How does that translate to actual SQL? does LINQ end up retrieving all the rows and then extracting the required ones? or does it leverage things like TOP to only retrieve the required subset?
Requesting Gravatar... Farrio Apr 14, 2009 9:05 PM
# re: Using jQuery Grid With ASP.NET MVC
Thanks Phil but I got an error when I just copied your code. It said object does not support the method or the property when it invoked jQuery("#list").jqGrid({
I'm pretty sure that I've pasted all js files and added the script elements. Can you help me?
Requesting Gravatar... Shiju Varghese Apr 14, 2009 10:10 PM
# re: Using jQuery Grid With ASP.NET MVC
Thanks Phil for the very useful post.
Requesting Gravatar... PK Apr 14, 2009 10:44 PM
# re: Using jQuery Grid With ASP.NET MVC
@born2code: I love Linq2Sql and I've had a huge amount of success with L2S + stored procs, so i'm not sure why you're not having much luck with that. Also, the linq SKIP and TAKE does make use of the TOP query and i think a where clause with count, i think. it's been ages since i looked at the sql it generates. it does NOT pull back all the records and THEN page those results. It only pulls back the 'page' required.

@Phil: another great article! I have a quick question about this post. DISCLAIMER: I've not downloaded the project source, so i've not looked at the full code. The action method you've written is GREAT for some AJAX magic. What about when you first hit the resource (eg. /home/index) .... how do u populate the grid then? You do not? you have an empty grid and then make another call, via ajax, to populate it? I'm a huge fan of ajax but would you consider populating the grid when the resource first gets hit, reducing one more call. I know it sounds like like this is another case for premature optimization (anti-pattern), but I generally like to render the view fully if possible and use ajax for user interaction. I would love your thoughts on this.

-PK-
Requesting Gravatar... Zachary Snow Apr 15, 2009 12:10 AM
# re: Using jQuery Grid With ASP.NET MVC
The line:

jQuery(document).ready(function(){
});

can be shortened to:

jQuery(function(){
});

and even further if you use the $:

$(function(){
});
Requesting Gravatar... Craig Stuntz Apr 15, 2009 4:15 AM
# re: Using jQuery Grid With ASP.NET MVC
Weird. I just started a series of posts on using the same component yesterday:

blogs.teamb.com/craigstuntz/2009/04/14/38200/

I'm using a completely different method to send data to the grid, however. The grid supports two different ways of sending the data in JSON format: a cell array (what you use in this post) and with named columns. I'm going to show the second method, along with extension methods for IQueryable which allow you to transform any IQueryable integrated data, without having to know the names of the individual fields on the contained element type. Thus, it works really well for anonymous types, which I find very well suited for JSON serialization, since they can be guaranteed not to have cycles in the object graph.

Anyway, thanks for posting this, and I will get the rest of my own series up soon!
Requesting Gravatar... Joe Reynolds Apr 15, 2009 5:30 AM
# re: Using jQuery Grid With ASP.NET MVC
Very nice stuff. However, is there any way to use this jquery plugin (or some other) to gain more control of the formatted output? I'm looking for something like this that allows data display/paging using MVC in a way similar to what can be done with the ASP.NET Repeater control.
Requesting Gravatar... tawani Apr 15, 2009 5:35 AM
# re: Using jQuery Grid With ASP.NET MVC
@born2code
Ling2Sql uses something like this in SQL 2005:

DECLARE @PageNum AS INT;
DECLARE @PageSize AS INT;
SET @PageNum = 2;
SET @PageSize = 10;

WITH OrdersRN AS
(
SELECT ROW_NUMBER() OVER(ORDER BY OrderDate, OrderID) AS RowNum
,OrderID
,OrderDate
,CustomerID
,EmployeeID
FROM dbo.Orders
)

SELECT *
FROM OrdersRN
WHERE RowNum BETWEEN (@PageNum - 1) * @PageSize + 1
AND @PageNum * @PageSize
ORDER BY OrderDate, OrderID;
Requesting Gravatar... Craig Stuntz Apr 15, 2009 6:29 AM
# re: Using jQuery Grid With ASP.NET MVC
Here are the extension methods I wrote to turn any IQueryable into data suitable for the grid:

blogs.teamb.com/craigstuntz/2009/04/15/38212/
Requesting Gravatar... born2code Apr 15, 2009 6:43 AM
# re: Using jQuery Grid With ASP.NET MVC
@PK && @Tawani: Thanks for the feedback about Linq2SQL optimization. I was hoping it does this. I use MySQL and not MS SQL much these days (i use what ever my clients require and recently it is all MySQL). There is no good support from the MySQL native ADO.NET Connector for the Entity Framework. nHibernate and others do not support Stored procedures.

I tried other frameworks/driver combinations and ran into various issues with each. I am developing production applications so I cannot have an "almost working" solution, or something that would behave unexpectedly, on occasion, during real life usage.
I had one of those with the anti forgery tokens when deployed to a shared host and all of the sudden started getting ViewState encryption errors because the anti forgery token code used (at the time) a shared cookie.
Couple more occurences like this and the client loses confidence in MVC (and my work) :)

@Joe Reynolds: it is very easy to roll out your own "repeater" control with jQuery and MVC. You use jQuery like Phil did to retrieve the rows of a specific page (you can pass the page number to the MVC method) and then write a User Control that binds to the data. You can either bind the JSON results from your method, or you can use ActionResults to return a partial view and replace the content of a div. pretty cool, and i do it all the time.

Requesting Gravatar... born2code Apr 15, 2009 6:46 AM
# re: Using jQuery Grid With ASP.NET MVC
@PK && @Tawani: Thanks for the feedback about Linq2SQL optimization. I was hoping it does this. I use MySQL and not MS SQL much these days (i use what ever my clients require and recently it is all MySQL). There is no good support from the MySQL native ADO.NET Connector for the Entity Framework. nHibernate and others do not support Stored procedures.

I tried other frameworks/driver combinations and ran into various issues with each. I am developing production applications so I cannot have an "almost working" solution, or something that would behave unexpectedly, on occasion, during real life usage.
I had one of those with the anti forgery tokens when deployed to a shared host and all of the sudden started getting ViewState encryption errors because the anti forgery token code used (at the time) a shared cookie.
Couple more occurences like this and the client loses confidence in MVC (and my work) :)

@Joe Reynolds: it is very easy to roll out your own "repeater" control with jQuery and MVC. You use jQuery like Phil did to retrieve the rows of a specific page (you can pass the page number to the MVC method) and then write a User Control that binds to the data. You can either bind the JSON results from your method, or you can use ActionResults to return a partial view and replace the content of a div. pretty cool, and i do it all the time.

ha ha, to prove my point, i got a server error 500 trying to post the comment... and when i tried to resend I got a message about a 1 minute delay between comments... exactly the things i do not need in a production environment :)
Requesting Gravatar... Mario Apr 15, 2009 10:01 AM
# re: Using jQuery Grid With ASP.NET MVC
Thanks Phil, really usefull post!
Requesting Gravatar... devinterview Apr 15, 2009 4:05 PM
# re: Using jQuery Grid With ASP.NET MVC
You made my day. Love jquery and MVC.
Requesting Gravatar... Haacked Apr 15, 2009 9:06 PM
# re: Using jQuery Grid With ASP.NET MVC
@PK Yeah, this is just the approach that jQuery grid takes where it makes the extra request for data. I personally think it's fine in this case since you can render the full page quickly and the data just pops in when it's ready.

There are other Ajax grids that have different behaviors. I know there's an ExtJS one that "ajaxifies" an HTML table. That one might fit the approach you want better.

Requesting Gravatar... Pure Krome Apr 16, 2009 5:35 AM
# re: Using jQuery Grid With ASP.NET MVC
Thanks Phil for the reply :)
Requesting Gravatar... Chris Apr 16, 2009 6:27 AM
# re: Using jQuery Grid With ASP.NET MVC
Hey Phil,

Do you ever run into an issue where you add certain js files from jQuery and intellisense ($ && jQuery) go away? I've noticed this with sometimes the order of the js files or which ones I include, and in this case, included exactly the ones you have, but not getting intellisense for anything.

Ideas?
Requesting Gravatar... Thanigainathan.S Apr 16, 2009 6:38 AM
# re: Using jQuery Grid With ASP.NET MVC
Hei,

Thats really rocking. Customers will be happy if they see these kind of things.

Thanks,
Thani
Requesting Gravatar... Craig Stuntz Apr 16, 2009 7:59 AM
# re: Using jQuery Grid With ASP.NET MVC
JqGrid actually does have a feature which takes a regular HTML table and turns it into a jqGrid, data and all. However, this means that you are now supplying data to the grid in two very different ways. First, via an aspx/ascx and secondly via JSON. That makes the code to do this somewhat odd, although with enough work it could probably be rolled together so that the two bits of code used the same model.

www.secondpersonplural.ca/.../_2h30t8wte.htm
Requesting Gravatar... Peter.O Apr 16, 2009 9:21 AM
# re: Using jQuery Grid With ASP.NET MVC
Hi Phil,
The post was easy to follow and worked the first time.

I don't know if it's an 'acquired taste' or just pain all the way. But when I finished, it left this sore feeling that there's too much 'string'iness around it. Table nesting really does feel cleaner than the jqGrid implementation.

In addition, table nesting and LINQ paging affords me easier server-side control over how much data actually gets fetched from the server per request ie: one page full.

Cool theming support there but it has a low priority.
Requesting Gravatar... Yazilim Apr 17, 2009 3:04 PM
# re: Using jQuery Grid With ASP.NET MVC
Pretty cool, using this and a little bit of blogs.teamb.com/craigstuntz/2009/04/17/38229/ than i have a nice solution :)
Requesting Gravatar... Jack Apr 18, 2009 2:05 AM
# re: Using jQuery Grid With ASP.NET MVC
Cool, the style is quite fashion!
Requesting Gravatar... Irfan Apr 18, 2009 2:54 AM
# re: Using jQuery Grid With ASP.NET MVC
I am writing a series of similar articles for ExtJS. Please have a look at this article:

www.dottostring.com/.../adding-support-for-net-...

But I am using WebMethods instead of writing my code in Page_Load and think this would increase efficiency of your site.
Requesting Gravatar... Tracker1 Apr 18, 2009 10:25 PM
# re: Using jQuery Grid With ASP.NET MVC
Where were you a month ago.. lol. BTW the beta jqGrid ties in with the gQueryUI's skinning much better... May have to do a followup article. (note: I had to adjust jqGrid a bit, and added some additional love for attaching an external form's data to the jqGrid requests. Nice article though, took me a bit of effort to figure out the returns needed for jqGrid based on the PHP code. Also, there's a few othe jquery based grids out there, imho jqGrid offers the best usability.
Requesting Gravatar... Tomas Apr 19, 2009 5:29 AM
# re: Using jQuery Grid With ASP.NET MVC
First of all I must say it's a great blog that most certainly is great help to a lot of people out there.
The question I have is how can you make this unobtrusive? I know that almost everyone has javascript enabled today, but is there an easy way to help those that hasn’t? I guess that the solution is to make the check on the server and provide a different view if javascript is not enabled, or can it be made easier?

Requesting Gravatar... Mike Apr 19, 2009 11:22 AM
# re: Using jQuery Grid With ASP.NET MVC
Getting the same error as Farrio during the initial display of the grid when the page loads "Microsoft JScript runtime error: Object doesn't support this property or method"

Has anyone else got this a figured it out?
Requesting Gravatar... Rob Apr 19, 2009 1:01 PM
# re: Using jQuery Grid With ASP.NET MVC
I am also getting "Microsoft JScript runtime error: Object doesn't support this property or method", I am pretty new to JQuesry so I apologise if this is something that is obvious but can't seem to fix it at the moment.
Requesting Gravatar... jyotishka bora Apr 19, 2009 1:28 PM
# re: Using jQuery Grid With ASP.NET MVC
very nice..
Requesting Gravatar... Paresh Apr 19, 2009 9:18 PM
# re: Using jQuery Grid With ASP.NET MVC
Hi,

Yeah i too had got the same issue that Mike and Rob are facing currently.In firebug it shows the error as "jQuery("#list").jqGrid is not a function." I verified the path of all the js files included.
please let me know if there is any solution to fix this issue.
Requesting Gravatar... Andrey Apr 20, 2009 3:06 PM
# re: Using jQuery Grid With ASP.NET MVC
Guys (those how have problem with "jqGrid is not a function" error message), you need to go to jquery.jqGrid.js file and update the line:

>> var pathtojsfiles = "js/"; // need to be ajusted
Update it to whatever your path to js files is. For me, this action fixed the problem.
Requesting Gravatar... Praveen Apr 20, 2009 6:17 PM
# re: Using jQuery Grid With ASP.NET MVC
Thanks for the article, Phil. I am trying to implement jqGrid within the standard ASP .NET application using MS AJAX web methods. How does one go about it? Do you have solutions you can point me to?

Thanks for your time.

Regards,
Praveen
Requesting Gravatar... Jim Apr 21, 2009 12:29 PM
# re: Using jQuery Grid With ASP.NET MVC
Where is the source code for this post? I really want a working version to compare exactly what I have done wrong to get rid of the errors talked about above? I have checked each and every js file path so doubt that is the problem.
Requesting Gravatar... Andrey Apr 21, 2009 2:22 PM
# re: Using jQuery Grid With ASP.NET MVC
Everyone, please be aware that jqGrid number pages from 1, not from 0!
So page parameter for the first page is actually 1.

If you utilize, for example class PagedList - it accepts as input page index which is assumed to be zero-based.
Requesting Gravatar... Haacked Apr 22, 2009 12:33 PM
# re: Using jQuery Grid With ASP.NET MVC
@Jim I posted the link to the source at the bottom of the post. You can grab it from here.
Requesting Gravatar... Jim Apr 23, 2009 1:36 AM
# re: Using jQuery Grid With ASP.NET MVC
Brilliant! Thanks a lot
Requesting Gravatar... Paresh Apr 23, 2009 6:01 AM
# re: Using jQuery Grid With ASP.NET MVC
Hi Guys,

Does the solution suggested by Andrey solve the above error?
It doesn't worked for me.
Requesting Gravatar... Will Apr 23, 2009 6:54 AM
# re: Using jQuery Grid With ASP.NET MVC

Hi Guys,

Does the solution suggested by Andrey solve the above error?
It doesn't worked for me.


Worked for me. I changed:

var pathtojsfiles = "js/";

to

var pathtojsfiles = "/Scripts/js/"
Requesting Gravatar... Petr Apr 27, 2009 12:52 AM
# re: Using jQuery Grid With ASP.NET MVC
Without enabled js unaccessible, google can't index content, very poor implementation ...
Requesting Gravatar... Sean Apr 27, 2009 8:13 AM
# re: Using jQuery Grid With ASP.NET MVC
@born2code: According to LINQPad,

Purchases.OrderBy (p => p.Price).Skip (5).Take(3)

becomes

SELECT [t1].[ID], [t1].[CustomerID], [t1].[Date], [t1].[Description], [t1].[Price] FROM ( SELECT ROW_NUMBER() OVER (ORDER BY [t0].[Price]) AS [ROW_NUMBER], [t0].[ID], [t0].[CustomerID], [t0].[Date], [t0].[Description], [t0].[Price] FROM [Purchase] AS [t0] ) AS [t1] WHERE [t1].[ROW_NUMBER] BETWEEN @p0 + 1 AND @p0 + @p1 ORDER BY [t1].[ROW_NUMBER]
Requesting Gravatar... BeullaBoris Apr 28, 2009 5:19 PM
# re: Using jQuery Grid With ASP.NET MVC
I am still getting the object not supported issue. I have changed the var pathtojsfiles and everytime I run and debug it changes the path back to the original.

Any help?
Requesting Gravatar... Zachary Scott May 03, 2009 1:47 PM
# re: Using jQuery Grid With ASP.NET MVC
Two huge benefits this article brings:

1.) The C# class encoded as Json is fantastic. I was wondering how you could serialize Linq to SQL Classes. This provides one very nice way to do it.

2.) The disclaimers help understand where these techniques fit in the Agile and DDD realms. They hint where they fit.

What would be good would be to tie these articles in to a big map of all the technology. For example, a dot that would explain "sanatize your inputs", a dot that explains a repository, and a dot that says "you are here".

These blog posts like this are extremely helpful.
Requesting Gravatar... Fernando Soruco May 11, 2009 8:18 AM
# re: Using jQuery Grid With ASP.NET MVC
how do transform c# json to visual basic .net for example : thisvar jsonData = new {
total = totalPages,
page = page,
records = totalRecords,
rows = new[]{
new {id = 1, cell = new[] {"1", "-7", "Is this a good question?"}},
new {id = 2, cell = new[] {"2", "15", "Is this a blatant ripoff?"}},
new {id = 3, cell = new[] {"3", "23", "Why is the sky blue?"}}
}
};
how to pass it to visual basic .net , help plz
Requesting Gravatar... Ian May 15, 2009 7:59 AM
# re: Using jQuery Grid With ASP.NET MVC
Has anyone had any problems with the pager not working with jqgrid

I set up jqgrid with a URL to fetch the data and it returns the first page fine I can page by typing a number in the page box which fires the ajax call to the server and returns the correct page but pressing the previous and text buttons does nothing. The ajax call doesn't even fire.

Requesting Gravatar... Ian May 18, 2009 3:08 AM
# re: Using jQuery Grid With ASP.NET MVC (my last comment)
I solved my own problem obviously in Phils demo code he hadn't returned the total number of pages and therefore the paging in the jqGrid didn't work.
Requesting Gravatar... Chris Jun 02, 2009 3:07 AM
# re: Using jQuery Grid With ASP.NET MVC
Never occurred to me to use JSON with JQuery. That's awesome!
Requesting Gravatar... Vladimir Kelman Jun 03, 2009 8:34 AM
# re: Using jQuery Grid With ASP.NET MVC
In "Dynamic Linq Query library" article ScottGu said, "In a future blog post I'll delve further into building dynamic LINQ queries, and discuss other approaches you can use to structure your code using type-safe predicate methods". He never did it, but those type-safe methods are described here www.albahari.com/nutshell/predicatebuilder.aspx and here http://tomasp.net/blog/dynamic-linq-queries.aspx. I hope we can use them instead of Dynamic Linq Query library to avoid using strings.
Requesting Gravatar... stan4th Jun 08, 2009 7:54 AM
# re: Using jQuery Grid With ASP.NET MVC
Hi,
Thanks for this article.
I tried finding in the documentation - is there any feature for providing filtering of rows?
Cheers
Requesting Gravatar... Sigurður Bjarnason Dec 18, 2009 2:53 PM
# re: Using jQuery Grid With ASP.NET MVC
Very nice article, but i think that the source has been corrupted because i am unable to extract the zip file.
Requesting Gravatar... mike Dec 21, 2009 12:56 PM
# re: Using jQuery Grid With ASP.NET MVC
Have been trying to get this to work with no success. When debugging I am noticing that the url:'/Home/GridData/' is getting called. There is no data in the grid however? Could this be because I am using a masterpage. I have also tried '../../home/griddata' with no success.
Requesting Gravatar... mike Dec 21, 2009 2:57 PM
# re: Using jQuery Grid With ASP.NET MVC
Solved my own error. Anyone using MVC2 Must use this to allow Get Json.

return Json(jsonData, JsonRequestBehavior.AllowGet);

Now the grid is finding 3 rows but text is displayed.
Requesting Gravatar... mike Dec 21, 2009 3:03 PM
# re: Using jQuery Grid With ASP.NET MVC
Works now! Thanks for the great tutorial!
Requesting Gravatar... Ryan Dec 24, 2009 11:05 AM
# re: Using jQuery Grid With ASP.NET MVC
Thanks mike, this one has been bugging me for about an hour and I saw your post, and wala...
Requesting Gravatar... Prajakta Dec 30, 2009 4:41 AM
# re: Using jQuery Grid With ASP.NET MVC
How to pass the querystring to the action method?
Requesting Gravatar... Jason Jan 04, 2010 4:24 PM
# re: Using jQuery Grid With ASP.NET MVC
I tried to download the source code and am getting an error when I try to open the ZIP file.

The error:
"The archive is either in unknown format or damaged."
Requesting Gravatar... Ajay Jan 05, 2010 12:32 AM
# re: Using jQuery Grid With ASP.NET MVC
Hi,

the attached code zip file is corrupted. Can't open the file. Phil, is there any way to get to the zip file?

Thanks.
Requesting Gravatar... Tom Jan 20, 2010 11:20 AM
# re: Using jQuery Grid With ASP.NET MVC
the download errors when i try to open the zip. It seems the file is corrupted. Can you post a new download please?
Requesting Gravatar... Luka Jan 21, 2010 3:19 AM
# re: Using jQuery Grid With ASP.NET MVC
the file seems to be corrupted.can you reupload it?
Requesting Gravatar... Michael Ceranski Jan 22, 2010 11:18 AM
# re: Using jQuery Grid With ASP.NET MVC
My initial impression of jqGrid was WOW. I actually started using it in a application that I was developing until I realized that I was doing too much work to make it perform tasks that should be rather simple. IMHO, there is still no replacement for good ol' HTML tables customized with a little jQuery and/or Ajax.

Just from reading the comments, it seems like people are having problems making jqGrid work. From personal experience the documentation for jgGrid is sparse and not very well done.

If it helps anyone, I also wrote an article about using jqGrid with MVC on my blog Using jqGrid with asp.net MVC.
Requesting Gravatar... Bats Ihor Jan 27, 2010 3:45 AM
# re: Using jQuery Grid With ASP.NET MVC
Phil, please update the sources file....
Requesting Gravatar... Sam Feb 09, 2010 3:55 PM
# re: Using jQuery Grid With ASP.NET MVC
Thanks Mike for this MVC2 tip:
return Json(jsonData, JsonRequestBehavior.AllowGet);
Requesting Gravatar... Peg Feb 22, 2010 9:17 AM
# re: Using jQuery Grid With ASP.NET MVC
The download is still corrupted...would you mind uploading a valid .ZIP???
Requesting Gravatar... WhamBham Feb 27, 2010 6:09 AM
# re: Using jQuery Grid With ASP.NET MVC
The download source file is corrupt. Can you please reissue a new archive to this article? Cheers.
Requesting Gravatar... Eduardo Feb 27, 2010 9:57 AM
# re: Using jQuery Grid With ASP.NET MVC
Hi Phil !
The example in zip format is corrupted, is possible to put the example in a correct file ?
Thanks in advance

Eduardo
Requesting Gravatar... liji Mar 03, 2010 2:05 AM
# re: Using jQuery Grid With ASP.NET MVC
thanks mike,solved my problem
Requesting Gravatar... haacked Mar 03, 2010 9:53 PM
# re: Using jQuery Grid With ASP.NET MVC
Hi All, I fixed the download link. Sorry for the corrupted file.
Requesting Gravatar... Qamar Uddin Mar 17, 2010 6:47 PM
# re: Using jQuery Grid With ASP.NET MVC
Hi guys,
Anyone has the VB.Net version of the controller code of this project
Requesting Gravatar... TWaldron Mar 19, 2010 12:39 PM
# re: Using jQuery Grid With ASP.NET MVC
Thanks Mike for the MVC2 Comment. This was killing me.
Anyone know how I could pass a date parameter for to the controller as well?
I want to have a datepicker that will control the data in the grid based on the date picked.
Requesting Gravatar... Ranjith Mar 26, 2010 3:13 AM
# re: Using jQuery Grid With ASP.NET MVC
Hi,
I am using sample example in vb.net. but It throws error in(lambda parameter not in scope)

Dim jsondata = New With {.total = totalPages, .page = page, .records = totalRecords, _
.rows = (From Product In lobjProducts Select New With {.ProductID = Product.ProductID, _
.cell = New String() {Product.ProductID, Product.Title.ToString(), Product.Description.ToString(), Product.IsActive.ToString()}}).ToArray()}


I search a lot, nobody can implement in vb.net.

.cell = New String() ----here I didn't get the values.

please help me.



Requesting Gravatar... Chris Apr 26, 2010 11:56 AM
# re: Using jQuery Grid With ASP.NET MVC
One thing I noticed that gave me problems. Make sure you change...

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

...to the correct version. Mine was jquery-1.4.1.js, for example. Changed this and all was well.
Requesting Gravatar... Coding Pill Apr 28, 2010 2:08 PM
# re: Using jQuery Grid With ASP.NET MVC
Nice One Phil ... hope to repay you one day
Requesting Gravatar... Bhavin Patel May 06, 2010 6:10 AM
# re: Using jQuery Grid With ASP.NET MVC
hi Haack,
i have downloaded ur demo project and i worked on that and i run it but in out put it shows only empty grid no single data shows why its like that?whats a problem with it? i have made the similar project like you but the result was similar not a different.i got the data at the jsondata on home controller class but not shows on the output page.i am using the linq to sql.i tried your all the tree methods on the home controller class,i found the similar result.Can you guide me regarding that,so i can go ahead in MVC.

Regards,
Bhavin Patel
Requesting Gravatar... Ramesh Kadirisani May 10, 2010 1:31 PM
# re: Using jQuery Grid With ASP.NET MVC
Fix for .OrderBy(sidx + " " + sord) issue:

While working with this example, many users might have experienced the problem with the above line (I am newbie in .NET MVC world so please excuse me if the fix that i mentioned is not correct).

i used the following fix and thought could be useful to others:

//Comment the following lines
/*
var questions = context.Questions
.OrderBy(sidx + " " + sord)
.Skip(pageIndex * pageSize)
.Take(pageSize);
*/

//Add the following code
var question = (sord == "asc") ?
context.Questions
.OrderBy(new Func<Questions, IComparable>(Questions => (IComparable)GetPropertyValue(Questions,sidx)))
.Skip(pageIndex * pageSize)
.Take(pageSize)
:
context.Questions
.OrderByDescending(new Func<Questions, IComparable>(Questions => (IComparable)GetPropertyValue(tblElectionContest, sidx)))
.Skip(pageIndex * pageSize)
.Take(pageSize);


//Now add the following method in your controller
//(Author of this following method is : Kjetil Watnedal)

public object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}


Requesting Gravatar... Ramesh Kadirisani May 10, 2010 1:35 PM
# re: Using jQuery Grid With ASP.NET MVC
Fix for .OrderBy(sidx + " " + sord) issue:

While working with this example, many users might have experienced the problem with the above line (I am newbie in .NET MVC world so please excuse me if the fix that i mentioned is not correct).

i used the following fix and thought could be useful to others:

//Comment the following lines
/*
var questions = context.Questions
.OrderBy(sidx + " " + sord)
.Skip(pageIndex * pageSize)
.Take(pageSize);
*/

//Add the following code
var question = (sord == "asc") ?
context.Questions
.OrderBy(new Func<Questions, IComparable>(Questions => (IComparable)GetPropertyValue(Questions,sidx)))
.Skip(pageIndex * pageSize)
.Take(pageSize)
:
context.Questions
.OrderByDescending(new Func<Questions, IComparable>(Questions => (IComparable)GetPropertyValue(Questions, sidx)))
.Skip(pageIndex * pageSize)
.Take(pageSize);


//Now add the following method in your controller
//(Author of this following method is : Kjetil Watnedal)

public object GetPropertyValue(object obj, string property)
{
System.Reflection.PropertyInfo propertyInfo = obj.GetType().GetProperty(property);
return propertyInfo.GetValue(obj, null);
}
Requesting Gravatar... Bhavin Patel May 13, 2010 1:10 AM
# re: Using jQuery Grid With ASP.NET MVC
hi Ramesh
i tried you code because i got the error during the binding the JQGrid,it remove the error and shows the data on screen but i tried to sorting the column but its reject the result was similar not change anything in that.
why is like that?
can you guide me regarding that please...........
i am waiting for your response...
Requesting Gravatar... Ramesh Kadirisani May 27, 2010 11:03 AM
# re: Using jQuery Grid With ASP.NET MVC
hi Bhavani Patel,
sorry i did not check this blog in a while. i started using the dynamic linq library and found the work around much easier than the way i explained before. please check the following web site for reference:

weblogs.asp.net/...

if you are not sure on how to use dynamic linq library, please let me know.
Requesting Gravatar... Robin van der Knaap Jun 08, 2010 6:51 AM
# re: Using jQuery Grid With ASP.NET MVC
I created a HtmlHelper for jqGrid with a fluent interface. The helper implements most base properties, methods and events from jqGrid, including paging, sorting and toolbar searching.
You can read about it at here. Sample app here. Source code is hosted on github

Hope somebody will find it useful.
Requesting Gravatar... Manuel Castro Jun 15, 2010 6:05 PM
# re: Using jQuery Grid With ASP.NET MVC
You can create a link to your edit / delete actions with a custom formatter for the column, in you colModel define the name of the custom function:

[code]
{ name: 'EquiptmentID', index: 'EquiptmentID', width: 80, formatter: linkEdit },
[/code]

And later in your javascript code create the action link:
[code]
function linkEdit(cellvalue, options, rowObject) {
return "" + cellvalue + "";
}
[/code]
Requesting Gravatar... Mike Jul 17, 2010 10:39 AM
# re: Using jQuery Grid With ASP.NET MVC
Anybody get this working with entity framework 4?

LINQ to Entities does not recognize the method 'System.String ToString()' method, and this method cannot be translated into a store expression.

var jsonData = new
{
total = totalPages,
page = page,
records = totalRecords,
rows = (
from x in gridData
select new
{
i = x.noteid,
cell = new string[] { x.noteid.ToString(), x.username, x.addeddate, x.title, x.note }
}).ToArray()
};
Requesting Gravatar... James Jul 26, 2010 10:10 AM
# re: Using jQuery Grid With ASP.NET MVC
I am running into error when I tried to run the sample project. It says "A project with an output type of class library cannot be started directly. In order to debug this add an executable project which references the library project. Set the executable project as the start up project. "

What am I doing wrong? Please help.

Thanks in advance.
Requesting Gravatar... Leon Jul 26, 2010 2:32 PM
# re: Using jQuery Grid With ASP.NET MVC
This solution isn't work on VS2010 .Net 4.0. I don't know why. When I use debug tool I can see that data is sending into grid. But It isn't displaying on the View. Now I want to find new example or create myself solution....
Requesting Gravatar... shyelauto Jul 28, 2010 11:38 AM
# re: Using jQuery Grid With ASP.NET MVC
Thank you for your post. Very Glad that you shared this to us. It's some pretty great info. Valuable information I found, keep on posting.
Requesting Gravatar... Randy Kreisel Jul 31, 2010 1:40 PM
# Problem opening eh Haacked database
getting the following error when opening the database.

Additional information: The database 'C:\PROJECTS\VS9\JQGRID MVC SAMPLE\JQUERYGRIDWEB\APP_DATA\HAACKOVERFLOW.MDF' cannot be opened because it is version 655. This server supports version 612 and earlier. A downgrade path is not supported.

Using VS 2008

Any suggestions??
Requesting Gravatar... jeff00seattle Aug 03, 2010 12:20 AM
# re: Using jQuery Grid With ASP.NET MVC
If I build this project with VS 2008 MVC 1 and using simple GridData(), then presto! it works!

If I build this same project with VS 2010, which converts the solution to MVC 2 and also using GridData(), then blamo! The table appears but the rows do not populate.

What difference(s) would there be to cause this disparity?
Requesting Gravatar... severo Aug 14, 2010 11:30 AM
# re: Using jQuery Grid With ASP.NET MVC
jeff00seattle, same problem for me!!! The table appears but the rows do not populate.
Requesting Gravatar... nader hamzei Aug 18, 2010 2:30 PM
# re: Using jQuery Grid With ASP.NET MVC
here is the VB.net code for the controller that some have been asking for. While I hit the controller method for MVC, and I do return a valid JSONified package, I cant get the datagrid to show any values.

any ideas?

Dim jsonData = New With { _
Key .total = 1, _
Key .page = 1, _
Key .records = 3, _
Key .rows = New Object() {New With { _
Key .id = 1, _
Key .cell = New Object() {"1", "-7", "Is this a good question?"} _
}, New With { _
Key .id = 2, _
Key .cell = New Object() {"2", "15", "Is this a blatant ripoff?"} _
}, New With { _
Key .id = 3, _
Key .cell = New Object() {"3", "23", "Why is the sky blue?"} _
}} _
}
Return Json(jsonData)
Requesting Gravatar... nader hamzei Aug 18, 2010 2:56 PM
# re: Using jQuery Grid With ASP.NET MVC
OK, I seemed to have figured out why the data isnt coming back but it is hardly a good fix. here is the issue, If this code worked for you in MVC 1 and doesnt in VS2010 and MVC 2 that is because of changes in Json, in particular the "Get" method. this has been disallowed by default. The reason is Get can open you up to JSON Hijacking. To get the code to work, look at my previous post and change the last line to :

Return Json(jsonData, JsonRequestBehavior.AllowGet)

this will allow the data to return and get populated, BUT THERE IS A COST. NOW, you can possible be JSON Hijacked.

Phil, can u wiegh in on this? Should this be depricated?
Requesting Gravatar... Gabriel Aug 19, 2010 2:38 PM
# DOES NOT WORK
I have downloaded and run this sample many times. Tried to tweek it. Nothing puts data in the grid. Data is making it to the Json object but is not populating the grid. Has this been updated for VS 2010?
Requesting Gravatar... Gabriel Aug 19, 2010 3:06 PM
# DOES NOT WORK (Revisited)
Nevermind. I just read the previous post.

What do you have to say?

(will show your gravatar)
Please add 8 and 3 and type the answer here: