Building an Sencha’s ExtJS 4.0 MVC Application With Microsoft’s ASP.NET MVC3 Series / Basics

Part 1 (this) Basics (mostly server side)
Part 2 ExtJS Client Side Details

 

*For those who are intersted in this, I just posted a 3 part series on using ExtJS 4.2 with Microsoft’s new WebAPI Restful Interface.  The new WebAPI is more efficient on the server side and the coding to REST makes the ExtJS side simpler. (March 13, 2013)    Part 1

 

Introduction

In this series of articles, we will take the reference application build by the Sencha product team for using Sencha’s MVC pattern running with an ASP.NET 4.0 project (IIS in production).  The first article takes the reference Sencha MVC app and with almost no changes, makes it work with the ASP.NET Visual Studio 2010 project.  By default, the application works with JSON static files.  We change that to work with an ASP.NET MVC3 project.  The second article in the series embellishes the application to include a more real user experience by adding additional functionality and data.  The improved functionality includes both date and number columns as well as paging.  It also adds functionality for inserts and deletes which are left out of the base app from Sencha.

Visual Studio Project SenchaMVCASPNetSolution

 

The Final Project when running:

 

image

 

 

What Is Sencha’s MVC Application

I don’t want to spend a lot of time here explaining what Sencha does really well in there article but I feel a short explanation is helpful  (http://www.sencha.com/learn/the-mvc-application-architecture/).

So, here we go.  Basically ExtJS is a client side JavaScript framework which allows you to build the full user experience in JavaScript.  That is, all the grids, forms, tabs, etc. are all generated by a client side JavaScript library.  All that goes up and down from the server is JSON (after the JavaScript framework and code and assets are downloaded).  This means that on the client side, all the code for displaying a grid for example, reaching out for data, pushing data changes, etc. all need to be done on the client (browser).  Sencha’s ExtJS MVC pattern helps organize all these functions into a set of directories and functions that make building apps scalable.

Below is what Sencha’s app in Visual Studio looks like:

 

image

 

 

ASP.NET Implementation

The major change to the stock MVC app from Sencha is to change there Store class.  Here is the new Store Class.

 

image

And the JavaScript itself:

 1: var writer = new Ext.data.JsonWriter({

 

 2:     type: 'json',

 

 3:     encode: false,

 

 4:     listful: true,

 

 5:     writeAllFields: true,

 

 6:     returnJson: true

 

 7: });

 

 8:

 

 9: var reader = new Ext.data.JsonReader({

 

 10:     totalProperty: 'total',

 

 11:     successProperty: 'success',

 

 12:     idProperty: 'Id',

 

 13:     root: 'Data',

 

 14:     messageProperty: 'message'

 

 15: });

 

 16:

 

 17: var proxy = new Ext.data.HttpProxy({

 

 18:     reader: reader,

 

 19:     writer: writer,

 

 20:     type: 'ajax',

 

 21:     api: {

 

 22:         read: '/UserInfo/Get',

 

 23:         create: '/UserInfo/Create',

 

 24:         update: '/UserInfo/Update',

 

 25:         destroy: '/UserInfo/Delete'

 

 26:     },

 

 27:     headers: {

 

 28:         'Content-Type': 'application/json; charset=UTF-8'

 

 29:     }

 

 30: });

 

 31:

 

 32: Ext.define('AM.store.Users', {

 

 33:     extend: 'Ext.data.Store',

 

 34:     model: 'AM.model.User',

 

 35:     autoLoad: true,

 

 36:     paramsAsHash: true,

 

 37:     proxy: proxy

 

 38: });

 

 

The primary change is to the reader.  Notice that the API’s are defined now to point the ASP.NET controller UserInfo.  Also, the column names have been changed to start with uppercase to be consistent with public properties in ASP.NET.  That is, id,name and email are now Id,Name and Email.

 

Now, we need to implement the controller on the ASP.NET.  Basically, we implement GET on the read and POST on the write.  The controller class in c# is as follows: (Visual Studio Solution Explorer first, then the controller code itself)

 

image

public class UserInfoController : Controller{    public JsonResult Get(int? start, int? limit)    {        using (var db = new Db())        {            start = start.HasValue ? start.Value : 0;            limit = limit.HasValue ? limit.Value : Int32.MaxValue;            int cnt = db.Users.Count();            var recs = db.Users.OrderBy(a => a.Id).                Skip(start.Value).Take(limit.Value).ToList();            return Json(new                            {                                Data = recs,                                total = cnt                            }, JsonRequestBehavior.AllowGet);        }    }

    [HttpPost]    public JsonResult Update(UserInfo data)    {        bool success = false;        string message = "no record found";        if (data != null && data.Id > 0)        {            using (var db = new Db())            {                var rec = db.Users.Where(a => a.Id == data.Id).                    FirstOrDefault();                rec.Name = data.Name;                rec.Email = data.Email;                db.SaveChanges();                success = true;                message = "Update method called successfully";            }        }

        return Json(new                        {                            data,                            success,                            message                        });    }}

 

Notice that the Get method returns a JsonResult.  This conveniently returns the data in JSON format.  Part of the secret sauce here is in the Db().  This app used Microsoft’s new EntityFamework CodeFirst. Following the standard CodeFirst model, we implement the simple c# code and it automagically creates the data tables (and data) in the database (my example uses SqlServer CE because it can be run without installing any database on your windows computer, the code is all in-memory).

If we look at the Model on the ASP.NET MVC3 side, you’ll notice the c# attributes and the DbContext that do the magic for you.  There are some excellent getting started guides on the web including one from Julie Lerman (walk through video: http://msdn.microsoft.com/en-us/data/gg715119 and http://msdn.microsoft.com/en-us/data/gg685467 ).

Here is the Visual Studio Solution Explorer for the model:

 

image

 

and here is the model code in c#:

namespace SenchaDesignerExtension.Models{    public class UserInfo    {        [Key]        [DatabaseGeneratedAttribute(DatabaseGeneratedOption.Identity)]        public int Id { get; set; }

        [MaxLengthAttribute(256)]        public string Email { get; set; }

        [MaxLengthAttribute(256)]        public string Name { get; set; }

    } }

 

and the actual repository which is in the file DbContext.cs (screen shot for brevity below, the code is attached in the example.

 

image

About Peter Kellner

Peter is a software professional specializing in mobile and web technologies. He has also been a Microsoft MVP for the past 7 years. To read more about Peter Kellner and his experience click here. For information about how Peter Kellner might be able to help you with your project click here.

Follow me:


Comments

  1. How can I delete a record?
    deleteUser: function (button) {
    var win = button.up(‘window’),
    form = win.down(‘form’),
    record = form.getRecord(),
    values = form.getValues();

    record.destroy();
    win.close();
    this.getUsersStore().sync();
    }

    This doesn’t seem to work

  2. Hi Peter
    How do it delete and create DATA Record? Thanks!

  3. Hi Peter,

    Thanks for this awesome article.
    I am asp.net developer but i am new to sencha framework. I have downloaded the attached project with this article. But i am not able to get how this project is working. When i run this project its showing me simple.html file. But project does not have a file with this name.

    I want to know where you have configured this so when some one run the project it will open simple.html instead of /Home/Index view.

    Thanks
    Shyanm

  4. Hi Roy,
    Thanks for the nice words. I had bigger plans for this series, but lately I’ve been spending a lot of time with the ExtJS Designer (latest beta) and really liking it. I’m guessing I’ll do blog posts on that which will be a big help I’m guessing for folks out there.
    -Peter

  5. This was a very nice article. I am not a programmer myself, I am a Network and system admin but I build a admin portal for my techs to use instead or the mmc’s from microsoft that uses asp.net 4 and extjs 3. I am looking at updating it and adding more to it and of course using extjs 4 now. Not being a programmer has been a challenge and part of my problem right now is trying to figure out how to use json. I am also thinking about using MVC this time around as well. In any case when do you plan to release the next article. I am really looking forward to making this work much smoother and taking more advantage of ext instead of using so much asp.net pages as the html body of the framework and instead just get the info back as like json and use as much of ext as possible.

  6. I’ve since learned more about knockout. Basically knockout is 100% client side which means that it is doing the same thing as the extjs store does so it really does not make any sense to integrate the two. What might be more interesting is integrating extjs with SignalR to get property notifiers working correctly from the server to the client and vica versa.

  7. Thanks John, I hope that we (sencha or us) can integrate something like Knockout into sencha’s events so that life is totally perfect. it’s non-trivial, but would be highly valuable. I’m at a big Microsoft event right now and I continue to push them to keep there api’s open.

  8. john mcfetridge says:

    oh I forgot , great article

  9. john mcfetridge says:

    sencha is a javascript framework that provides a lot of great UI widgets like grids. These work well crossbrowser and they also have some of the knockout data binding (XAML style) including observables. Knockout is data-binding lib and does a great job as it is making me miss Silverlight a little less although I sure miss the help of compile time checking. Sencha Touch is where the real power is as it lets u write a phone app once and deploy to all the phones

  10. sulfur_scratch says:

    Hi Peter,
    Thanks for this article, any idea when the part 2 will be published? I’d very much be interested in your thoughts on the:
    1. Separation of concerns as it relates to the Ext Control & the asp.net MVC controller.

    2. How .NET MVC Areas work with the new EXT MVC ‘architecture’ (if at all)

  11. Hi Denise,

    WCF is tricky. There are some other posts out there with similar examples in WCF that are probably worth looking at.

  12. Hi Peter,
    thanks for this article, I have been trying to make the MVC example work with a JSON WCF service but have not been successful. the example works with statis json data.. I was able to create another example where I tie the Sencha data grid to a JSON WCF service. In this instance, I did not use the Sencha MVC example, I leveraged Ext.Ajax.request instead.

    When I use the example above I get an empty response. Do you have any suggestions about this?

    I used your apporach mentioned above as well but could not get it to work. I am getting

  13. Hi Nick,
    I was not at DevConnections (I think that is what you meant), but from my understanding, knockout.js is about property change notifiers. I think the example they showed probably added some fancy JQuery Template builder which might be similar. I’m hoping to add the property notifier stuff down the line. It’s very nice!
    -Peter

  14. This sounds alot like knockout.js and everything else that was at the devexpress convention in vegas, no?

Trackbacks

  1. [...] So, it worked!  If you want to see the full source for this, keep an eye on the series of articles I’m now writing (only the first one is done, but probably, by the time you find this, I’ll have others done that include this Presidents example.  You can find the first one at the URL:  http://peterkellner.net/2011/11/04/building-an-senchas-extjs-4-0-mvc-application-with-microsofts-asp… [...]

Your Comments

*

Protected with IP Blacklist CloudIP Blacklist Cloud

Follow

Get every new post delivered to your Inbox

Join other followers: