Blog Posts Tagged Ext JS

Ext JS 3.0 Cookbook Book Review

I'm not sure if anyone else agrees but I sometimes find it hard to locate genuinely useful and practical Ext JS samples. Don't get me wrong, the Ext JS API documentation is second to none and provides a superb resource, but sometimes I just want to dig right into an application and see how it's been crafted, what best practices I should be following and how I can create DRY code. And do you know what? I find the Ext JS samples to be a little terse and not so well crafted. I understand it is likely that they are deliberately written this way so as to not bury the point of the sample but it is a time consuming process to digest, merge and/or re-factor the elements and snippets that interest you into a coherent and well written application.

What we need is some kind of reference. a reference that uses these sample elements, morsels and snippets as building blocks. a reference that binds and bakes these building blocks into coherent examples and sample applications.

We need a cookbook. an Ext JS Cookbook!

Ext JS 3.0 Cookbook

 

The Ext JS Cookbook by Jorge Ramon is full of step-by-step recipes to bake up some solid Ext JS code. Early pages in the book tackle some Ext JS and OO JavaScript basics though in no way is Jorge trying to provide a primer for developers. In fact he's simply reviewing the more basic ingredients and methods we'll need in order to better understand the rest of the book. I would have preferred these early pages to be less verbose - these early code samples were overly detailed. I don't need to see the the whole HTML document in the examples. just the important bits, please.

After those early pages, the book soon settles into a nice style that is easy to read. Each recipe is laid out in a way that makes it easy to dip into and quickly find the facts. A typical recipe is comprised of the following sections:

  • What You're Going to Achieve.
  • How To Do It.
  • How It Works.
  • There's More.

As the book progresses so does the complexity of the examples and recipes. Jorge takes us through the basics of the Ext JS toolkit and widgets providing some great insight and very very practical and useful sample code. Subsequent examples leverage or reference knowledge from previous chapters so we can quickly see how to combine recipes and techniques to create complex Ext JS applications. Importantly we learn how to engineer these techniques using established design patterns to create truly reusable and flexible code encapsulated as components, custom classes or plug-ins.

The last chapter discusses these design patterns in more detail and is an excellent primer for those interested in extending the Ext JS framework and creating plug-ins, modules and components. Additionally we learn how to enhance our application's performance and our user's experience.

All in all this is a great book and a fantastic resource for any Ext JS developer.

Published: Tuesday, 08 December 2009 09:23 PM by Steve

Tags: JavaScript Ext JS

Comments: 1 Comment

Ext JS 3.0 Cookbook

The good people at Packt Publishing have sent me a complimentary copy of their latest Ext JS book - Ext JS 3.0 Cookbook.

A brief look through indicates that it's very well laid out with clear and concise example code. I'd say it's appropriate for those already experienced in RIA development using Ext JS.

I'm looking forward to publishing a much more detailed review of this book so watch this space.

Ext JS 3.0 Cookbook

Published: Thursday, 05 November 2009 08:37 PM by Steve

Tags: JavaScript Ext JS

Comments: 0 Comments

Using Ext JS Grids with ASP.Net MVC - Basic Example

Following my post "Ext JS JsonStore and Linq to JSON Gotcha" I've had a few people asking for a more complete example of how to use Ext JS Grids and data stores (in particular the JsonStore) with ASP.Net MVC and LINQ to SQL. Since writing that blog post I've learnt a lot more about the ASP.Net MVC framework and the Ext JS framework so I thought it would be helpful to publish a complete working demo. So, here's an example that displays a simple Ext JS Grid populated from the Northwind database Products table. The example shows how to use an Ext JS Grid with a JsonStore that supports server side paging and sorting.

Download this example as a working Visual Studio 2008 MVC (Version 1.0) application.

Requirements

Overview

So take a look at the code. It's very simple and straightforward! Here's what you should see when you run the project.

MVC ExtJS Grid screen shot

In brief the Index action method of the Products controller handles a vanilla HTTP GET request for the Products index page (/Products/). The view it returns is an almost empty page that simply exposes an element that we can render the Ext JS GridPanel to.

When the index page loads, the load event creates the Ext JS components needed including the JsonStore. It then renders the grid and loads the data store thus triggering an AJAX request to the same URL (this time as a POST, which is the only method supported by the JsonStore component). A different Index action method in the controller handles the POST and if it's an Ajax request it pulls the products from the database and returns JSON in a format expected by the JsonStore.

[AcceptVerbs(HttpVerbs.Post)]
      public ActionResult Index(int Skip, int Take, string SortDir, string Sort)
      {
      if (Request.IsAjaxRequest())
      {
      var products = productsRepository.GetAllProducts();

      var results = (new
      {
      totalRecords = products.Count(),
      products = products.OrderBy(Sort + " " + SortDir).Skip(Skip).Take(Take)
      });

      return Json(results);
      }
      else
      {
      return RedirectToAction("Index");
      }
      }

Some Points of Interest

Where I define the JsonStore component in the ext-lib.js file you will notice I have re-defined the default paging parameter names to match my own code behind. Also notice I am redefining some JsonReader parameters (totalProperty and root) to match the JSON data returned by the controller action method. These steps aren't strictly necessary for this example but I have included it for reference. Alternatively you could use the default Ext JS parameter names and ensure your c# code matches.

Northwind.ProductStore = function(config) {
      Northwind.ProductStore.superclass.constructor.call(this, Ext.apply({
      paramNames: {
      "start": "Skip",
      "limit": "Take",
      "sort": "Sort",
      "dir": "SortDir"
      },
      totalProperty: 'totalRecords',
      root: 'products',
      remoteSort: true,
      autoLoad: false,
      id: "ProductID",
      method: "POST"
      }, config));
      };

The config parameter of the ProductStore constructor above is used to allow us to pass in additional, or override the existing, configuration parameters of the component. 

Also in ext-lib.js file you will notice a column renderer method. This is a helper function called during  grid rendering to format the data in certain columns. When the columns are specified in the ProductColumnModel you will see I have configured the Stock column to use the stockRenderer method to render the column data.

The stockRenderer method shows how you can reference the data row currently being rendered by the grid and manipulate the HTML rendered in the grid cell. Here I simply add a style to any products that have a stock level less than the reorder level and that are also discontinued.

The column renderer for the Price column uses a built in formatter to render the data as a currency.

The Discontinued column uses a special Ext JS column type to render the boolean value.

Summary

Well, I hope you have found this interesting and helpful. I'm hoping to expand on some of the concepts here and provide examples of some more advanced capabilities and features I have implemented using the ASP.Net MVC and Ext JS frameworks.

Published: Tuesday, 21 July 2009 04:48 PM by Steve

Tags: MVC Ext JS ASP.Net Linq

Comments: 8 Comments

Ext JS JsonStore and Linq to JSON Gotcha

Here's a little gotcha that had be scratching my head for a moment. I was testing the Grid component of the excellent Ext JS framework when I ran into a problem loading the JSON result into the grid.

It seemed simple enough - populate the grid from JSON data returned by a controller action method. When I ran the code the grid wasn't populated: the Ext JSONReader was throwing an error "root is undefined". I checked and double checked everything but could not see what the problem was.

Here's the JavaScript to create the JsonStore for the grid:

      var ds = new Ext.data.JsonStore({
      url: '/Home/GetData',
      totalProperty: 'totalRecords',
      root: 'requests',
      id: "ReqNo",
      fields: ['Division', 'Department'],
      listeners: {
      loadexception: function(proxy, store, response, e) {
      alert(e.message);
      }
      }
      }); 

Here's the controller method that returns the JSON:

      public JsonResult GetData(int? start, int? limit)
      {
      limit = limit ?? 25;
      start = start ?? 0;


      string dataPath = HttpContext.Server.MapPath("~/Data/TestData.xml");
      XDocument xDoc = XDocument.Load(dataPath);
      var results = from requests in xDoc.Descendants("requests")
      select new
      {
      totalRecords = requests.Elements("request").Count(),
      requests = (from request in requests.Elements("request")
      select new NBWeb.Models.Request
      {
      Division = request.Element("Division").Value,
      Department = request.Element("Department").Value
      }).Skip((int)start).Take((int)limit)
      };
      return this.Json(results);
      }

And here's an example of the JSON it emits:

      [{
      "totalRecords":200,
      "requests":[
      {"Division":"Division 1","Department":"Department 5",},
      {"Division":"Division 2","Department":"Department 4",},
      {"Division":"Division 3","Department":"Department 5",},
      {"Division":"Division 4","Department":"Department 6",},
      ]
      }]

      

Eventually, upon examining the JSON for the tenth time, it dawned on me - the entire JSON data was nested in a redundant outer array. So the JsonStore root property was not being found - it was looking for:

obj["requests"]

but would need to look for:

obj[0]["requests"]

So it was the controller returning slightly malformed JSON. It's a bug in my code - I need to return the inner result of the Linq select rather than the entire result. So I need to take the FirstOrDefault record from the results, like so:

      public JsonResult GetData(int? start, int? limit)
      {
      limit = limit ?? 25;
      start = start ?? 0;

      string dataPath = HttpContext.Server.MapPath("~/Data/TestRequests2500.xml");
      XDocument xDoc = XDocument.Load(dataPath);
      var results = (from requests in xDoc.Descendants("requests")
      select new
      {
      totalRecords = requests.Elements("request").Count(),
      requests = (from request in requests.Elements("request")
      select new NBWeb.Models.Request
      {
      Division = request.Element("Division").Value,
      Department = request.Element("Department").Value,
      }).Skip((int)start).Take((int)limit)
      }).FirstOrDefault();

      return this.Json(results);
      }

And here's the corrected JSON it emits (note the absence of the outer square brackets):

      {
      "totalRecords":200,
      "requests":[
      {"Division":"Division 1","Department":"Department 5",},
      {"Division":"Division 2","Department":"Department 4",},
      {"Division":"Division 3","Department":"Department 5",},
      {"Division":"Division 4","Department":"Department 6",},
      ]
      }

Seems like a dumb mistake to make but it took a bit of debugging to find it - hopefully this post will save someone out there some time.

Published: Friday, 24 October 2008 05:22 PM by Steve

Tags: MVC Ext JS Gotcha ASP.Net

Comments: 5 Comments