Saturday, June 11, 2011

MVC3: Basic JQGrid Example

JQGrid seems to be one of the most fully featured grids in JQuery land.  Further to this, it seems like MS is putting some money into the development of features for this particular grid.  The following is a basic example of how to get JQGrid running with MVC3.

The scenario is as follows.  Lets say you have a small amount of data (say less than 500 rows) and you would like to display this to your user.  The easiest way to do this is to load all the data client side and then let jqgrid take care of the rest.  The client-side sorting and filtering will be really quick as it will not require another server call.  This will also reduce load on your server.

JQuery requires that the response format be very specific.  From the examples, it looks something like this.

total: 1,
page: 1,
records: 20,
rows: [ {id:1 cell:[data1 data2]} ... ]

You can customize the names of the fields with the jsonreader property, but the concept is still the same.

With the row number being pretty low and no need for server side interaction (read save/update) we can load all the data directly into the grid via the model.  Here is some sample code to do that.

public class HomeController : Controller
        public ActionResult Index()
            var model = new IndexModel();
            model.Data = new JavaScriptSerializer().Serialize(CreateGridData(100,100));
            return View(model);

        private dynamic CreateGridData(int count, int rows)
            var totalPages = Math.Ceiling((double)count / rows);
            return new
                total = Convert.ToInt32(totalPages),
                page = 1,
                records = count,
                rows = CreateGridItems(count)

        private dynamic CreateGridItems(int count)
            var gridItems = Enumerable.Range(0, count).Select(x => new GridItem() { Name = "Name" + x, Number = "Number" + x }).ToArray();
            var results = new List<object>();
            foreach (var gridItem in gridItems)
                    id = gridItem.Name,
                    cell = new []{gridItem.Name,gridItem.Number}
            return results;


The model is quite simple:

public class IndexModel
        public dynamic Data { get; set; }

And the JS code (just a very basic grid, you will probably want more options than this)

$(document).ready(function () {
            datastr: '@Html.Raw(@Model.Data)',
            datatype: 'jsonstring',
            colNames: ['Name', 'Number'],
            colModel: [
                { name: 'id' },
                { name: 'Number' }
            height: '100%'


The JavaScript serializer converts our object into proper JSON.  MVC3 has some built in XSS projection, and by default, will escape out the data.  You can get around this by using the @Html.Raw feature.  See MVC3 Xss. You now have a jqgrid with all the data loaded.  You can add paging/sorting/filtering that will all work client-side.

Course Review: Developing Application for the Java EE Platform

Last year, I was still doing a lot of java stuff at my current position.  Most of my Java knowledge (as I'm sure is true of most java developers) had been organically grown via many online tutorials, blog posts, tool documentation, and looking at old code.  The latter is probably one of the best and worst ways to learn a language.

I really struggled in trying to understand how all the different java components fit together.  Sure, I could create a web.xml, but how did it all really work?  I wanted to learn more about the specifications that drive the Java platform.  With this goal in mind, I took the course Developing Application for the Java EE Platform from Oracle university. 

The course had many cons, but I did learn a thing or two.

1)  The electronic voice that you hear while navigating through this course is truly brutal. You learn very quickly that there is a transcript button, where you can read exactly what the "voice" is saying.  There is also a mute button, a must find in the first couple of minutes.  I swear that Oracle should pay a dollar for every time you have to hear " or navigate by using the tab and spacebar keys".

2) No course notes.  I really really like going back later on and reviewing course notes, especially for reference.  With the SANS courses, you get course notes with all the slides and some of the "transcript".  Really helpful for when you are trying to master skills later on.

3)  Very high level.  The course was designed as more of an intro course, so I knew what I was getting into.  I found the course didn't really focus on how to do things, or common ways a developer would take advantage of the various (and I mean various) Java specifications.  For example, it is great to know that JAXB is an architecture for xml binding, but what do you do with it? What are some common implementations?

4)  Session timeout.  The player would still function (if say, you were within a module and just clicking the next button) even if you had your session timed out.  This was great as I could start a section and then leave to go do something.  I would come back to find the player still functional and assume that my session was still valid.  I would click through the rest of a module and finish only to find that my session was timed out and that I would have to redo everything I just did.  It was pretty frustrating because of the next point.

5)  Complete means clicking through every page.  Yawn.

1)  Lots of good information from the "source".  It is one thing to read some tutorial on how to do things, and another to actually read about what the specification is actually supposed to do.

Overall, I learned a fair bit from this course, even if it was just solidifying what I already knew.  I'm not sure I would take another oracle course as the delivery format was really hard for me to deal with.