Using Ext. Js with ASP.NET

View this thread on: d.buzz | hive.blog | peakd.com | ecency.com
·@cues·
0.000 HBD
Using Ext. Js with ASP.NET
#### What Will I Learn?
In this tutorial I am going to show you how Ext.Js compares to JQuery and how we can use it with ASP .NET.

#### Requirements


- ASP.NET Core
- Ext. Js
- JQuery
- Ext livegrid

#### Difficulty
Intermediate


#### Tutorial Contents
1- JQuery vs Ext Js
- The billing
- Ease of use
- Performance, robustness and scalability
- So which one wins?<br>
<br>
2- Scratch the surface of Ext Js
- Ext Ready?
- The Ext Element
- Ext.xTemplate
- Ajax comes into play
- Ext.Grid<br>
<br>
3- The driving force of ASP .NET<br>
<br>
4- Finally, an Ext JS Grid Panel

### Using Ext. Js with ASP.NET

In this tutorial I am going to show you how Ext.Js compares to JQuery and how we can use it with ASP .NET.

The world of web is always a-a-changing, the garden of JavaScript has been expanding, with libraries of all sorts springing up every day, though only some of them are flourishing and staying into major contenders. jQuery is the widely popular one, enjoying a thriving community and ever-growing list of plug-ins contributed by enthused developers; Ext has a much low profile and is exclusively developed and owned by Sencha.

## JQuery vs Ext Js
#### The billing
To say the obvious, they are billed differently. jQuery is marketed as The write less, do more JavaScript library; Ext Js is branded as A cross-browser rich internet application framework. You know from the start, Ext Js took themselves more seriously, not to mention it does not offer free license for commercial use.

#### Ease of use
I have to say, jQuery is much, much more intuitive, because the way it turns the familiar css conventions into simple yet powerful selectors. If you know JavaScript and css, you will be able to pick up jQuery in no time. On the other hand, Ext is a full-blown framework, it tastes more like a heavy-handed programming language than scripts, quite some of syntax feels like directly culled from c/c#/java. It employs all of the object-oriented methodology. It has a lot of built in templates and controls. It is a beast that is hard to warm up to (for me), but once you have a hang with it, it would be your powerful beast.

#### Performance, robustness and scalability
Sencha and my colleagues claim Ext has better performance. From my research, it seems to be inconclusive. But I do think Ext wins on the side of robustness and scalability.


#### So which one wins?
I have been using Ext Js for half an year; I cannot say I am fully converted.

I still miss JQuery, I mean, I miss the jQuery community. Whenever I typed a question about jQuery, google always happily churning up a long list solutions even better-phrased questions, but with Ext Js, my only hope lies with my colleagues and dive down into the Ext API documentation (which is comprehensive however highly geeky); On the other hand, Ext does have a awesome set of utilities and templates and solid object-oriented core for you to inherit, encapsulate or whatever to your heart's content, which is good for applications meant for complex and continuously evolving situations.



My imaginary warfare between jQery and Ext Js is like that of Mac and PC. Ext Js smacks of more the elite, geeky flavor of Mac, but jQuery is like PC, maybe a little clumsy, but widely popular, still rules the day.

## Scratch the surface of Ext Js
First and foremost, you should know, every quest about Ext probably will begin and end in the Ext Js API (http://docs.sencha.com/extjs/6.5.3/). By the way, the Ext Api documentation itself is developed with Ext Js and show-cases the power and agility of the framework.

![](https://steemitimages.com/DQmejtGUW9wA6FmxyAhjwTthqqK8nRNxGLwqgSMUecnyMu6/image.png)

#### Ext Ready?
In jQuery, the single most important event in the document ready event and the one piece of code that you must know is

```
$(document).ready(function(){
   // now we are ready to
 });
```

Likewise, in Ext, only when the dom is ready the ball starts rolling.

```
Ext.onReady(function() { 
Ext.MessageBox.alert('Hi', 'Yes, we are good to go'); 
});
```

#### The Ext Element
The Ext way of manipulating HTML element is to wrap it in then dress it up then arm it with all sorts of utilities, to make a Ext.Element. And Ext element is so dear and essential to Ext, it is called the "heart of Ext Js".

The way to get an element is Ext.get() or Ext.fly().

Let's say you have a div.

```<div id="el1">I am a plain thing</div>```

You can get it like this:

```var el = Ext.get('el1')```

or

```var el = Ext.fly('el1')```

After that, you can start working on your element.

```
//set size
El.setSize(200, 150).
//add listeners
Ext.fly(el).on("click", function (e, t) {
        alert('why you click me?');
    });
//Create a child for it, give the child a full set of attributes (id, html, css class, etc.)
var c = el.createChild({id: 'child1', html: 'I am a child', cls: 'child'});
//Then remove it
c.remove();
```

#### Ext.xTemplate

We all hate we have to spit out the same code over and over again, however computer is always good at repetitions, all we need is some sensible instructions or a good Ext XTemplate, like this:

1. A sample Ext.XTemplate

```
var myTpl = new Ext.XTemplate(
            '<tpl for=".">',
            '<div class="color color{id}"></div> <div class="label">{label}</div>',
            '</tpl>'
        )
 var myData =  [
                { id: 1, label: 'ABC' },
                { id: 2, label: 'CNN' },
                { id: 3, label: 'CBS' },
                { id: 4, label: 'NBC' },
                { id: 5, label: 'Whatever' }
          ],
// apply template here
var c = el.createChild({id: 'child1', html: myTpl.apply(myData), cls: 'child'});
```

## Ajax comes into play
Behind all of the ever-more-exciting JavaScript libraries, it is really AJAX that makes them so exciting and sexy. No wonder jQuery has a great many ways to AJAX, from the very simple ones, get/post to the very comprehensive and fully configuarable one like ajax.load. You can google out a zillion of posts of how to do jQuery Ajax.

Ext has a lot too. Moreover, Ext has a class to manage the data Ext.Data.Store, with two subslasses: JsonStore, SimpleStore. SimpleStore is meant to manage data that is simple and local, for example, array. A typical use of it is a Ext native combo box, as the following

#### 2. A dummy Ext ComboBox

```
var mySimpleStore = new Ext.data.ArrayStore({ // 1 
data : [ 
['test123'], [' testABC'], ['testxyz'], ['testcdx'] 
], 
fields : ['name'] 
}); 
Var combo = { 
xtype : 'combo', 
fieldLabel : 'Select a name', 
store : mySimpleStore, 
displayField : 'name', 
typeAhead : true, 
mode : 'local'}
```
On a side note, Ext combobox is one of cool ext controls that supports autocomplete, remote-loading, paging and many other features.

Quite often, you probably will find that a combobox (or most other controls) with dynamic data is much more needed, so you would employ Ext JsonStore and call it like the following:

```
var store = new Ext.data.JsonStore({
    url: 'getdata.ashx',
    root: 'result',
    fields: ['name', 
'url', 
		{name:'size', type: 'float'}, // a field with datatype specified 
		{name:'lastmod', type:'date'}]// a field with datatype specified
});
```

#### Ext.Grid
Any web is about successful presentation of data, grid is forever one of most requested presentation form, and all major languages and scripts strive to provide the most robust, powerful, appealing grid that is capable of doing great many things, including editing, search, paging, sorting, expanding, collapsing . So does the gridview of ASP .net. So does the Ext GridPanel.

Ext gridPanel really rocks. And go to Sencha website, they can never demo enough grid for you. Steal a couple of screenshots here:

![](https://steemitimages.com/DQmRbnS9i9N8CuwaX5ZTMijfXKN13sYLMfyWmPzCVdcv4ek/image.png)

![](https://steemitimages.com/DQmdCixXHfBiKhP2qhbL1pEu6S3Z2YVfaG5ibeL6HZ9FUqP/image.png)



For a grid like that you actually do not need to sweat too much. We will have a dummy example later to illustrate this point.

Moreover, other than the "traditional" Ext GridPanel, there is one even more amazing Ext Grid: livegrid. Ext.ux.Livegrid is an ExtJS user extension that connects to a database backend and renders large sets of data into a grid, without the need of paging. It dynamically fetches next batch of data rows as you scroll. Server requests for pre-buffering data are only invoked when needed - your application will be able to virtually render thousands of rows of data at one time, and users can browse through this data without performance loss.

You may check out the Ext livegrid at http://www.ext-livegrid.com/.

## The driving force of ASP .NET
Once upon a time, ASP .net wants to be the king that rules the front end (the client-side UI presentation) and the backend (the server-side data, the business logic ...,), the easy, complex and complicated. Now, at least for me, ASP .net pretty much is only in charge of the backend, harness the limitless computing powers and ever-evolving frameworks on the server side, fetching, manipulating and marshalling data to the client.

That is what we do here, created a data layer to set up the data, then use a handler to bridge the data and ui.

Let's run down the data set up quickly.

#### 3. Data classes

```
public class Employee
{
    public int Id { get; set; }
    public string Name { get; set; }
    public string Address { get; set; }
    public Employee()
    {
    }
    public Employee(int id, string name, string address)
    {
        Id = id;
        Name = name;
        Address = address;
    }
}
```

A generic class with a total property that gives the size of the recordset and the dynamic class that will hold the real data. This is required by the Ext Js Gridpanel, so the resulting JSON object will have 2 pieces of necessary information: total and the actual data.

```
public class Result
{
    public int Total { get; set; }
    public dynamic Employees { get; set; }
}
```

A business logic class that prepare the data. Here we just use a dummy service to cook up some fake employees.


```
public class DataService
{
    public static Result GetEmployees()
    {
        const int totalRecords = 35;
        var employees = new List<employee>();
        for (int i = 0; i < totalRecords; i++)
        {
            employees.Add(new Employee(i,
                                       string.Format("f lastname {0}", i),
                                       string.Format("Fictional Street {0}", i)));
        }
        var paged = new Result { Total = totalRecords, Employees = employees };
        return paged;
    }
}
```

The super important glue (the handler) that provides just the right stuff (JSON object).

```
public class GetData : IHttpHandler
{
    #region IHttpHandler Members
    public bool IsReusable
    {
        get { return true; }
    }
    public void ProcessRequest(HttpContext context)
    {
        context.Response.ContentType = "application/json";
        var serializer = new JavaScriptSerializer();
        context.Response.Write(serializer.Serialize(DataService.GetEmployees()));
    }
    #endregion
}
```


The standard handler method ProcessRequest has only three crucial lines of code.

First, context.Response.ContentType = "application/json"; set the response content type to be json; second, call a JavaScriptSerializer to work; third, ask the serializer to serialize our data into objects that can be digested by EXT Js. It is like saying: hey, I want it to be in Chinese; Get me a Chinese translator; Translate it now so I can understand, duh!

You can check out the JSON data returned from the httphandler using firebug.

![](https://steemitimages.com/DQmbiywmNfpMbozH3ug3j2qczeQ26sWzv4DJX8BBGX6PRBC/image.png)

## Finally, an Ext JS Grid Panel
Finally, let's set up a super dummy Ext Js Grid panel!

It is always satisfying to be able to set up something, even a dummy grid. With Ext Js Grid, all you need to do is just configure a few things: The data store, the column model, title, sort, etc., as the following:

```
Ext.onReady(function () {
    var store = new Ext.data.JsonStore({
        url: 'http://localhost/MvcApplicationCSharp/GetData.ashx',
        root: 'Employees',
        idProperty: 'Id',
        totalProperty: 'Total',
        fields: ['Id', 'Name', 'Address'],
        remoteSort: true,
        autoLoad: true
    });
    var cm = new Ext.grid.ColumnModel({
        columns: [
                    { header: 'Id', width: 50, dataIndex: 'Id'},
                    { header: 'Name', width: 200, dataIndex: 'Name'},
                    { header: 'Address', width: 200, dataIndex: 'Address'}
            ],
        defaults: {
            sortable: true,
            scope: this,
            menuDisabled: true,
            align: 'left'
        }
    });
    var grid = new Ext.grid.GridPanel({
        title: 'Employees',
        store: store,
        colModel: cm,
        renderTo: Ext.get('divGrid'),
        width:500,
        height: 350,
        border: true,
        loadMask: true
    });
});
```

With the set up, you get the following Ext Grid:

![](https://steemitimages.com/DQmUGhtuxhWtAjHF1rGaEK8KifQiKX5nmfXgzT4Ef1t3KP6/image.png)

#### Summary
So in this tutorial, we have had a glimpse of Ext Js, the cross-browser JavaScript framework developed from Sensha, and how we can glue this framework on top of ASP .net. Hope you enjoy it, and give Ext Js a try if you have not.

<br /><hr/><em>Posted on <a href="https://utopian.io/utopian-io/@cues/using-ext-js-with-asp-net">Utopian.io -  Rewarding Open Source Contributors</a></em><hr/>
👍 , , , , , , , , , ,