RSS

ExtJS and ASP.NET MVC 3: CRUD DataGrid

23 Oct

This short tutorial will walk though the implementation of DataGrid using ExtJS 3.3.1 andASP.NET MVC 3. In this tutorial I focus more on the integration of the front-end, so you will not find any database code. Whenever we deal with data we usually create, read/retrieve, update or delete them. ExtJS provides a great data grid component and the ability to perform CRUD operation with very little coding. I used JSON as data format in the example below.

ExtJS DataGridExtJS DataGrid

Let’s start with the server-side by developing the data model and controller.

Controller:

01 public class ContactController : Controller
02 {
03     //
04     // GET: /Contact/
05
06     public ActionResult Index()
07     {
08         return View();
09     }
10
11     public JsonResult Load()
12     {
13         var contact = new List<Contact> {
14             new Contact("Smith","95746325","smith@me.com"),
15             new Contact("Adam","87291034","adam@me.com"),
16             new Contact("Eve","98271345","eve@me.com"),
17             new Contact("Chun Li","81728312","chun.li@me.com")
18         };
19         return Json(new
20         {
21             total = contact.Count,
22             data = contact,
23         }, JsonRequestBehavior.AllowGet);
24     }
25
26     [HttpPost]
27     public JsonResult Create(List<Contact> data)
28     {
29         //insert Create code
30         return Json(new
31         {
32             data = new Contact(data[0].Name, data[0].Phone, data[0].Email),
33             success = true,
34             message = "Create method called successfully"
35         });
36     }
37
38     [HttpPost]
39     public JsonResult Update(List<Contact> data)
40     {
41         //insert Update code
42         return Json(new
43         {
44             success = true,
45             message = "Update method called successfully"
46         });
47     }
48
49     [HttpPost]
50     public JsonResult Delete(List<string> data)
51     {
52         //insert Delete code
53         return Json(new
54         {
55             success = true,
56             message = "Delete method called successfully"
57         });
58     }
59 }

Data Model:

01 public class Contact
02 {
03     public string Id { getset; }
04     public string Name { getset; }
05     public string Phone { getset; }
06     public string Email { getset; }
07
08     public Contact(string pName, string pPhone, string pEmail)
09     {
10         this.Id = System.Guid.NewGuid().ToString();
11         this.Name = pName;
12         this.Phone = pPhone;
13         this.Email = pEmail;
14     }
15
16     public Contact() { }
17 }

ExtJS:

Now, you move on to the view and work on the ExtJS. First, you define the record type which matches the server-side object.

01 var Contact = Ext.data.Record.create([
02     {
03         name: 'Id',
04         type: 'string'
05     }, {
06         name: 'Name',
07         type: 'string'
08     }, {
09         name: 'Phone',
10         type: 'string'
11     }, {
12         name: 'Email',
13         type: 'string'
14     }
15 ]);

Now you need to setup the Writer and Reader

01 var writer = new Ext.data.JsonWriter({
02     encode: false,
03     listful: true,
04     writeAllFields: true
05 });
06
07 var reader = new Ext.data.JsonReader({
08     totalProperty: 'total',
09     successProperty: 'success',
10     idProperty: 'Id',
11     root: 'data',
12     messageProperty: 'message'  // <-- New "messageProperty" meta-data
13 }, Contact);

Then, setup a proxy to define the connection to the controller.

1 var proxy = new Ext.data.HttpProxy({
2     api: {
3         read: '/Contact/Load',
4         create: '/Contact/Create',
5         update: '/Contact/Update',
6         destroy: '/Contact/Delete'
7     },
8     headers: { 'Content-Type''application/json; charset=UTF-8' }
9 });

Hooks the above components (reader, writer, proxy) to the store.

1 var store = new Ext.data.Store({
2     id: 'user',
3     proxy: proxy,
4     reader: reader,
5     writer: writer,
6     autoSave: false
7 });

Add the data grid declaration

01 var grid = new Ext.grid.GridPanel({
02     store: store,
03     columns: [
04         { header: "Name",
05             width: 170,
06             sortable: true,
07             dataIndex: 'Name',
08             editor: {
09                 xtype: 'textfield',
10                 allowBlank: false
11             }
12         },
13         { header: "Phone No.",
14             width: 160,
15             sortable: true,
16             dataIndex: 'Phone',
17             editor: {
18                 xtype: 'textfield',
19                 allowBlank: false
20             }
21         },
22         { header: "EMail",
23             width: 170,
24             sortable: true,
25             dataIndex: 'Email',
26             editor: {
27                 xtype: 'textfield',
28                 allowBlank: false
29             }
30         }
31     ],
32     plugins: [editor],
33     title: 'Contacts DataGrid',
34     height: 300,
35     width: 510,
36     tbar: [{
37         iconCls: 'icon-user-add',
38         text: 'Add Contact',
39         handler: function () {
40             var e = new Contact({
41                 Name: 'New Friend',
42                 Phone: '(65) 89182736',
43                 Email: 'new@google.com'
44             });
45             editor.stopEditing();
46             store.insert(0, e);
47             grid.getView().refresh();
48             grid.getSelectionModel().selectRow(0);
49             editor.startEditing(0);
50         }
51     }, {
52         ref: '../removeBtn',
53         iconCls: 'icon-user-delete',
54         text: 'Remove Contact',
55         handler: function () {
56             editor.stopEditing();
57             var s = grid.getSelectionModel().getSelections();
58             for (var i = 0, r; r = s[i]; i++) {
59                 store.remove(r);
60             }
61         }
62     }, {
63         iconCls: 'icon-user-save',
64         text: 'Save All Modifications',
65         handler: function () {
66             store.save();
67         }
68     }]
69 });

Some observations:

  • When submitting data as JSON, set the headers “Content-Type” to “application/json” in the proxy object and set the encoding to false in the JsonWriter. If not, it will be treated as form submission.
  • Since I set the auto save to false. DataGrid will submit list of contact when there are 2 or more changes, however it will send a single object when there is 1 change. In order to make it consistent to send as list, set list full to true in the JsonWriter.
  • ASP.NET MVC 3 able to recognize the JSON without additional coding.

If you want to see the complete source code, download it from here. Hope it’s useful. :)

Happy hacking!

Referenced by: http://myxaab.wordpress.com/2011/02/20/extjs-and-asp-net-mvc-3-crud-datagrid/

Advertisements
 
1 Comment

Posted by on October 23, 2011 in Javascript, Web Application

 

One response to “ExtJS and ASP.NET MVC 3: CRUD DataGrid

  1. sabri

    November 15, 2011 at 10:25 PM

    Thank you for this tutorial,
    is what I can find another example but with a database?
    Thank you

     

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

 
%d bloggers like this: