Load data on forms with ExtJS and ASPNET MVC

Introduction

Now I’ve followed researching a lot about ExtJS support for rich Internet applications and nice user experience and the more I read about this library, the more I like it. S, I’ve decided to write this article to illustrate how to create an edit form in ExtJS and integrated with ASP.NET MVC framework. After researching a lot in order to know how to get request parameter from the URL string using Ext libraries, I’ve developed my own solution.

Getting started with the solution

We’re going to implement the Edit Employee use case for a Human Resources Management system. The Edit Employee use case description is as follows: A screen prompts the user to update valid information (whether optional or mandatory) for an existing employee such as employee identifier, full name, address, age, salary and department. The screen shows employee information by the employee identifier passed by the screen parameters.

This use case fits well to illustrate the main artifacts and steps for a solution using ExtJS and ASP.NET. The implementation strategy for this use case is to create an ExtJS form on the client-side to load data and send the updated data to the server to be processed. The server-side application is developed using ASP.NET MVC framework. The persistence layer will be Linq to represent business entities and to persist data to the database system. As the development environment we’re going to use Microsoft Visual Studio.NET 2008 and as the database system Microsoft SQL Server 2005/2008.

Open Visual Studio.NET 2008 and create an ASP.NET MVC application (see Figure 1).

Figure 1

Next step is to create the database schema for the solution. Our schema will contain two entities: employee and department. Let’s create the HumanResources database and the underlying tables and its constraints in order to maintain the data integrity. For this example, we also need some data on the tables (see Listing 1).

 

create table department

(

deptno varchar(20) primary key,

deptname varchar(50) not null,

location varchar(50)

);

create unique index undx_department_deptname on department(deptname);

 

insert into department

values(‘HQ-200′,’Headquarter-NY’,’New York’);

insert into department

values(‘HR-200′,’Human Resources-NY’,’New York’);

insert into department

values(‘OP-200′,’Operations-NY’,’New York’);

insert into department

values(‘SL-200′,’Sales-NY’,’New York’);

insert into department

values(‘HR-300′,’Human Resources-MD’,’Maryland’);

insert into department

values(‘OP-300′,’Operations-MD’,’Maryland’);

insert into department

values(‘SL-300′,’Sales-MD’,’Maryland’);

 

create table employee

(

empno varchar(20) primary key,

fullname varchar(50) not null,

address varchar(120),

age int,

salary numeric(8,2) not null,

deptno varchar(20) not null,

constraint fk_employee_department_belong_rltn foreign key(deptno)

references department(deptno)

);

create unique index undx_employee_fullname on employee(fullname);

 

insert into employee

values(‘EMP-0001′,’John Doe’,’20 Madison St.’, 32, 3000.99, ‘HQ-200’);

Listing 1

Then let’s create a Linq to SQL Classes item inside the Model folder to define the structure of the entities and the persistence mechanism. The object definition in Linq to SQL is shown in the Figure 2.

Figure 2

Next step is to develop the EmployeeRepository class to manage the data access logic to the employee table (CRUD operations). Regarding to our use case, we only need to implement the read by employee identifier and update operations (see Listing 2).

using System;

using System.Data;

using System.Configuration;

using System.Linq;

using System.Web;

using System.Web.Security;

using System.Web.UI;

using System.Web.UI.HtmlControls;

using System.Web.UI.WebControls;

using System.Web.UI.WebControls.WebParts;

using System.Xml.Linq;

 

namespace LoadDataOnForm_ExtJS_ASPNETMVC.Models

{

public class EmployeeRepository

{

private HumanResourcesDataContext _ctxHumanResources = new HumanResourcesDataContext();

 

public employee FindByKey(string empno)

{

return (from emp in this._ctxHumanResources.employees

where emp.empno == empno

select emp).SingleOrDefault();

}

 

public void Update(employee employee)

{

var origEmployee = this.FindByKey(employee.empno);

origEmployee.fullname = employee.fullname;

origEmployee.address = employee.address;

origEmployee.age = employee.age;

origEmployee.salary = employee.salary;

origEmployee.deptno = employee.deptno;

 

this._ctxHumanResources.SubmitChanges();

}

}

}

Listing 2

Now that we have defined the business logic’s artifacts, that is the business entities and the services that process the entities, we need to move onto the presentation layer. The implementation strategy for the presentation layer is ASP.NET MVC. MVC stands for model-view-controller. We have worked on the model piece of the architecture before. Now let’s define another important piece of the architecture: the controller.

Right-click on the Controllers folder in the Solution Explorer window and select Add|Controller option from the context menu. Set EmployeeController as the name (see Figure 3).

Figure 3

Now let’s go to the presentation piece to define the graphical interface using ExtJS JavaScript library. The first step is to download and copy the distribution of ExtJS inside the Scripts directory. For our solution, we only need ext-all.js file, ext-base.js file and the resources directory (see Figure 4).

Figure 4

Now let’s include this library in our project. For this purpose, let’s go to the Site.Master page and adding the references to the ExtJS files inside the head HTML element (highlighted in yellow in the Figure 14). As well, we need to add a <asp:ContentPlaceHolder> tag element as container of the customized JavaScript and CSS code for each page (highlighted in green in the Listing 5).

<head runat=”server”>

<title><asp:ContentPlaceHolder ID=”TitleContent” runat=”server” /></title>

<link href=”../../Content/Site.css” rel=”stylesheet” type=”text/css” />

 

<!– Include the ExtJS framework –>

<link href=”../../Scripts/ext/resources/css/ext-all.css” rel=”stylesheet” type=”text/css” />

<script type=”text/javascript” src=”../../Scripts/ext/ext-base.js”></script>

<script type=”text/javascript” src=”../../Scripts/ext/ext-all.js”></script>

<!– Placeholder to include CSS and JS files customized for each page –>

<asp:ContentPlaceHolder ID=”Scripts” runat=”server” />

</head>

Figure 5

Now let’s add the view to present the form to edit the data related to one employee. Go to the EmployeeController controller and right-click on the Index action method and select Add View option from the context menu. Click on the Add button on Add View dialog box (see Figure 6).

Figure 6

In order to implement the ExtJS form, we need to add a JavaScript file to the Scripts directory (see Figure 7).

Figure 7

Then include the JavaScript file and add a div element (with id=employeeeditform) into the Index.aspx view (see Listing 4).

<%@ Page Title=”” Language=”C#” MasterPageFile=”~/Views/Shared/Site.Master” Inherits=”System.Web.Mvc.ViewPage” %>

 

<asp:Content ID=”Content1″ ContentPlaceHolderID=”TitleContent” runat=”server”>

Index

</asp:Content>

 

<asp:Content ID=”Content2″ ContentPlaceHolderID=”MainContent” runat=”server”>

 

<h2>Edit Employee form</h2>

<div id=”employeeeditform”></div>

 

</asp:Content>

 

<asp:Content ID=”Content3″ ContentPlaceHolderID=”Scripts” runat=”server”>

<script type=”text/javascript” src=”../../Scripts/employee_editform.js”></script>

</asp:Content>

 

Listing 3

Now it’s time to go to the employee_editform.js file and write some code in JavaScript to configure the ExtJS form and its underlying widgets.

The first step is to define the form. The properties are self-descriptive. In this case, the url property points to the UpdateEmployee action method on the EmployeeController controller. This method is also accessed using POST HTTP verb (see Listing 6).

var form= new Ext.FormPanel({

title:’Edit Employee Form’,

renderTo: ’employeeeditform’,

width: 400,

url:’employee/updateemployee’,

defaults:{xtype:’textfield’},

bodyStyle:’padding: 10px’,

Listing 4

The items property is the list of widgets for the fields of the form. Here the default widget is textfield (this is specified in the defaults property). The first field is employee number which is required (specified by the allowBlank property) textfield. The second field is the fullname which is also a required textfield. The address field is an option textarea. The age field is an optional numberfield. The salary field is a required numberfield. And finally, the department number field (see Listing 7).

          items:[

{fieldLabel:’Employee ID’,name:’empno’, allowBlank:false},

{fieldLabel: ‘Fullname’,name: ‘fullname’, allowBlank:false},

{xtype: ‘textarea’,fieldLabel: ‘Address’,name: ‘address’,multiline: true},

{xtype:’numberfield’,fieldLabel:’Age’,name:’age’},

{xtype:’numberfield’,fieldLabel:’Salary’,name:’salary’, allowBlank:false},

{fieldLabel: ‘Department ID’,name: ‘deptno’, allowBlank:false}

],

Listing 5

Then the buttons property is defined (see Listing 8). As you can see in order to save button will submit the data (each field and its value will be posted in the request parameter). This can be analyzed in details in my previous articles about forms in ExtJS and the way to submit its data. In this article, we don’t implement the UpdateEmployee action in the Employee controller in order to focus on the loading data logic.

        buttons: [{

text: ‘Save’,

handler: function()

{

form.getForm().submit({

success: function(a, b)

{

Ext.Msg.alert(‘Success’, ‘ok’);

},

failure: function(a, b)

{

Ext.Msg.alert(‘Failure’, ”);

}

});

}

},

{

text: ‘Reset’,

handler: function()

{

form.getForm().reset();

}

}]

Listing 6

And the final ExtJS code is to load the initial data for the employee by passing the employee identifier by the id parameter.  After researching about getting request parameter from the URL string using Ext JS libraries, I have not found any code exceprt with the solution. The only thing that I’ve found is a little function written in pure JavaScript. After thinking myself about the problem nature, I’ve found out that the solution can’t be in any JavaScript code because the responsibility to process HTML request along with the request parameters resides in the server-side of the solution. So, I’ve figured out my own solution using global variables in JavaScript along with HTML request process model in ASP.NET MVC . The first step is to define a global JavaScript variable and assigned the value of the employee identifier taking from the request parameters. We do this by defining the global variable (before including the employee_editform.js library) in the script section of the Listing 3 in the Index.aspx view of the Index action in Employee controller (see highlighted in yellow in the Listing 7).

<asp:Content ID=”Content3″ ContentPlaceHolderID=”Scripts” runat=”server”>

<script type=”text/javascript”>

var emp_id = ‘<%=Request[“emp_id”] %>’;

</script>

<script type=”text/javascript” src=”../../Scripts/employee_editform.js”></script>

</asp:Content>

Listing 7

The next step is to define the data load ExtJS load logic to load data from the GetEmployee action in the Employee controller and specify to send the employee identifier by the request parameter empno and the value of empno request parameter is taken from the previous defined global variable emp_id as shown highlighted in yellow in the Listing 8.

    form.getForm().load({

url: ‘/employee/getemployee’,

method: ‘GET’,

params: {’empno’: emp_id},

failure: function(form, action) {

Ext.Msg.alert(“Load employee data failed”, action.result.errorMessage);

}

});

Listing 8

Then, you have the complete employee_editform.js file (see Listing 8).

Ext.ns(’employeeditform’);

 

Ext.BLANK_IMAGE_URL = ‘../ext/resources/images/default/s.gif’;

 

employeeditform.FormTutorial = {

init: function(){

//Begin of code   here

Ext.QuickTips.init();

var form= new Ext.FormPanel({

title:’Edit Employee Form’,

renderTo: ’employeeeditform’,

width: 400,

url:’/employee/updateemployee’,

defaults:{xtype:’textfield’},

bodyStyle:’padding: 10px’,

items:[

{fieldLabel:’Employee ID’,name:’empno’, allowBlank:false},

{fieldLabel: ‘Fullname’,name: ‘fullname’, allowBlank:false},

{xtype: ‘textarea’,fieldLabel: ‘Address’,name: ‘address’,multiline: true},

{xtype:’numberfield’,fieldLabel:’Age’,name:’age’},

{xtype:’numberfield’,fieldLabel:’Salary’,name:’salary’, allowBlank:false},

{fieldLabel: ‘Department ID’,name: ‘deptno’, allowBlank:false}

],

buttons: [{

text: ‘Save’,

handler: function()

{

form.getForm().submit({

success: function(a, b)

{

Ext.Msg.alert(‘Success’, ‘ok’);

},

failure: function(a, b)

{

Ext.Msg.alert(‘Failure’, ”);

}

});

}

},

{

text: ‘Reset’,

handler: function()

{

form.getForm().reset();

}

}]

});

form.getForm().load({

url: ‘/employee/getemployee’,

method: ‘GET’,

params: {’empno’: emp_id},

failure: function(form, action) {

Ext.Msg.alert(“Load employee data failed”, action.result.errorMessage);

}

});

//End of code here

}

}

 

Ext.onReady(employeeditform.FormTutorial.init,employeeditform.FormTutorial);

 

Listing 9

Now let’s go to the EmployeeController controller and implement the corresponding action methods (see Listing 10).

using System;

using System.Collections.Generic;

using System.Linq;

using System.Web;

using System.Web.Mvc;

using System.Web.Mvc.Ajax;

using LoadDataOnForm_ExtJS_ASPNETMVC.Models;

 

namespace LoadDataOnForm_ExtJS_ASPNETMVC.Controllers

{

public class EmployeeController : Controller

{

private EmployeeRepository _repoEmployee = new EmployeeRepository();

 

//

// GET: /Employee/

 

public ActionResult Index()

{

return View();

}

 

//

// GET: /Employee/GetEmployee

[AcceptVerbs(HttpVerbs.Get)]

public ActionResult GetEmployee(string _dc, string empno)

{

try

{

var objEmployee = this._repoEmployee.FindByKey(empno);

var results = (new

{

success = “true”,

data = (new

{

empno = objEmployee.empno,

fullname = objEmployee.fullname,

address = objEmployee.address,

age = objEmployee.age,

salary = objEmployee.salary,

deptno = objEmployee.deptno

})

});

return Json(results);

}

catch (Exception)

{

var results = (new

{

success = “false”,

errorMessage = “Employee not found”

});

return Json(results);

}

}

 

//

// POST: /Employee/UpdateEmployee

[AcceptVerbs(HttpVerbs.Post)]

public ActionResult UpdateEmployee(employee employee)

{

string strResponse = String.Empty;

try

{

this._repoEmployee.Update(employee);

strResponse = “{success: true}”;

}

catch (Exception)

{

strResponse = “{success: false, error: \”An error occurred\”}”;

}

return Content(strResponse);

}

}

}

 

 

Listing 10

Now let’s run the solution (see Figure 8). You can see that we have sent the employer identifier EMP-0001 using the emp_id request parameter in the URL string.

Figure 8

Conclusion

In this article, I’ve illustrated how to create an edit form in ExtJS and integrated with ExtJS JavaScript library and ASP.NET MVC framework.

Advertisements

4 thoughts on “Load data on forms with ExtJS and ASPNET MVC

  1. Pingback: MVP Factor

  2. Pingback: Fernando Garcia Lorea

  3. Pingback: Php script installation service

  4. Pingback: Hookah Supplies

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