Login | Register   
LinkedIn
Google+
Twitter
RSS Feed
Download our iPhone app
TODAY'S HEADLINES  |   ARTICLE ARCHIVE  |   FORUMS  |   TIP BANK
Browse DevX
Sign up for e-mail newsletters from DevX


advertisement
 

Create a Web App Using ASP.NET MVC 2.0 Framework

The benefits of using an MVC Framework is that it helps enforce a clean separation between the models, views, and controllers within a Web application.


advertisement
In this article I will show you how to create an ASP.NET Web Application using MVC 2.0 Framework. You'll recall that ASP.NET MVC 2.0 is the latest Microsoft framework for building web applications on top of the .NET framework 2.0, 3.0, 3.5 etc.

To set up the development environment, you need to install Visual Studio 2008/2010 Beta 2, SQL Express 2005 (freely downloadable from MSDN) and MVC 2.0 Framework. I have named my web application "Employee Master Information".

Using this application you can enter new employee data, edit existing employee data, can view specific employee data, and delete any employee from the database. The application is also using the ASP.NET membership provider for creating new user and authenticating an existing user and for Client Side validation JavaScript has been used.



Creating MVC Project, Database, and Data Model

In my previous ASP.NET MVC 2.0 Article, I discussed how to create an MVC Web Application using Visual Studio 2008 editor. In this article "MyMvcSample" is the name of my project created using VS 2008(.NET framework 3.5). Once you create the MVC 2.0 Web Site using Visual studio 2008 the next step would be Creating database and data models.

Right Click on the 'App_Data' folder of your project and add a new "SQL Server Database" object to your solution. If you don't have "SQL Express" installed in your development box, you will not get that item in the "Template" window. Name of your SQL Express database as MySampleDatabase.mdf, once you click the "Add" button a new database will be added in 'App_Data' folder. Now open the "Server Explorer" from the view menu; you will see MySampleDatabase.mdf database already there. Right Click on the "Tables" object under MySampleDatabase.mdf database and a new table named "tblEmployee". Add the following columns to "tblEmployee" table.

EmployeeName nvarchar(100)
EmployeeSalary numeric(18, 2)
EmployeeId int (Primary Key)
Department nvarchar(100)
Age int
Skillset nvarchar(1000)
Role nvarchar(50)

For the primary key column you need to change two properties: change "Identity Specification" from 'No' to 'Yes' and "Identity Increment" from 0(zero) to 1(one). After creating the table, enter a few sample data for testing purpose.

Next you need to create a Data Model -- right click on your 'Model' folder and add a New Item. Select "ADO.NET Entity Data Model" from the template list. In this example "DataModel.edmx" is the name of my Model. Click "Add" to add that Model to your solution. The Next screen is a wizard that will guide you to add data source for the Model your have just created. Select "Generate from Database" and click Next.

On the next screen you need to select the appropriate data source, select the previously created "MySampleDatabase.mdf" database from the list and provide a name for the data source. Your solution's web.config file will have an entry under "ConnectionStrings" tag with the data source name and the connection string, which is auto generated. In this example my connection name is "MySampleDatabaseEntities". On the next, check tblEmployee and provide your Model Namespace name.

Once your Model has been created, open DataModel.edmx in the Model viewer. This viewer will help you view the Model data source and field mappings between Model and database. You can also alter Model properties, filed name and data type using Model viewer. This "Employee" model will be used in Controller classes to add, edit and delete employee details in the database. DataModel.edmx is an ADO.NET Entity Framework object which reduces coding effort while insertion, updation or deleting to database. ADO.NET Entity Framework also supports LINQ, so you can write SQL like queries on top of your business objects, no need to write database stored procedures to fetch data.

Creating the Controller

Your controller will refer classes exists in Microsoft.Web.Mvc.Build.dll and Microsoft.Web.Mvc.dll. So before compiling your application check both the assemblies are already added in your bin.

For Add, Edit, Delete and View Details functionality of employee I have added 'Get' and 'Post' functions in my HomeController class. Each function in the controller class is associated with a View (.ASPX page), for example to see Employee List I have written "Index" function which returns Employee List and the list is shown in the view named "Index.aspx". To show a specific employee data, Details function has been called

Function Details(ByVal id As Integer) As ActionResult Dim objEditEmployee = (From c In objDatabaseEntities.EmployeeSet Where c.EmployeeId = id Select c).FirstOrDefault()            Return View(objEditEmployee) End Function

LINQ is used to query business object and find a specific Employee from the Employee List (Model).Using
"Return View" this employee object is sent back to the corresponding View. For Creating a New
Employee I have written both 'Get' and 'Post' Version of the "Create" method as well. The Get version of the method will
redirect to a blank Employee page/view where user will enter employee details and Post version of the "Create" function
will save employee details in the database using the Employee Model object, we have created earlier.

Proper client side validation has been added to the Create.aspx page for all the necessary input fields. Data will not be inserted into database if the newly entered Employee name already exists.

Function Create(ByVal objEmployee As Employee) As ActionResult            Try                Dim objExtEmployee = (From c In objDatabaseEntities.EmployeeSet Where                c.EmployeeName = objEmployee.EmployeeName Select c).FirstOrDefault()                If objExtEmployee Is Nothing Then                    objDatabaseEntities.AddToEmployeeSet(objEmployee)                    objDatabaseEntities.SaveChanges()                    Return RedirectToAction("Index")                End If            Catch                Return View()            End Try            Return RedirectToAction("Index") End Function

For editing employee details, I have also Created 'Get' and 'Post' version of Edit functions. But for edit employee I have added validation in the HomeController itself. Using Modelstate.Addmodelerror() function I am thronging an error to the corresponding view if validation fails.

        Protected Sub ValidateContact(ByVal EmployeeToValidate As Employee)            If EmployeeToValidate.EmployeeName.Trim().Length = 0 Then                ModelState.AddModelError("Employee Name", "Employee name is required                field.")            End If            If EmployeeToValidate.EmployeeId.ToString().Trim().Length = 0 Then                ModelState.AddModelError("Employee Id", "Employee Id is required field.")            End If            If (EmployeeToValidate.Department.Length = 0) Then                ModelState.AddModelError("Employee Department", "Employee Department is                required field.")            End If            If (EmployeeToValidate.EmployeeSalary.ToString().Length = 0) Then                ModelState.AddModelError("Employee Salary", "Employee Salary is required                field.")            End If            If (EmployeeToValidate.Age.ToString().Length = 0) Then                ModelState.AddModelError("Employee Age", "Employee Age is required field.")            End If            If (EmployeeToValidate.Skillset.ToString().Length = 0) Then                ModelState.AddModelError("Employee Skillset", "Employee Skillset is required                field.")            End If            If (EmployeeToValidate.Skillset.ToString().Length = 0) Then                ModelState.AddModelError("Employee Role", "Employee Role is required                field.")            End If        End Sub

For deleting an employee list, I have only added the Get version and in view added necessary Java Script validating (confirmation message).

Creating the Views

In an ASP.NET MVC application, all incoming browser requests are mapped to controller actions. A controller action might return a view. MVC views don't have any code behind file as like ASP.NET page. You can create views either right clicking on your controller post functions and select "view" option. You can Create a strongly type view using this option. The 2nd way to add a view to your project is right click on your View folder and add a new View. By default .ASPX pages without a code behind file (.CS/.VB) are the views. You can add an .ASCX file, HTML file as a view in your project.

In this example I have created 4 different views for Adding, Editing, Listing and Showing employee details and all are strongly typed views. I have used HTML helper class to create HTML objects in my views and Validation message for validating Client side data entry. The following code shows how to create a HTML Input control and add validation for that using HTML helper.

<div class="editor-field">                <%= Html.TextBoxFor(Function(model) model.EmployeeName) %>                <%= Html.ValidationMessageFor(Function(model) model.EmployeeName) %> </div>

I have used Html helper ActionLink for View navigation and Html.Encode () to encode special characters such as < and > into characters that are safe to display in a web page. HTML.Encode () has been recommended by Microsoft for JavaScript injection attacks. The following view code is written for adding a new Employee to database.

<asp:Content ID="Content2" ContentPlaceHolderID="MainContent" runat="server">    <h2>Create Employee</h2>    <%=""%>    <% Using Html.BeginForm()%>        <fieldset>            <legend>Details to Enter</legend>                        <div class="editor-label">                <%=Html.LabelFor(Function(model) model.EmployeeName)%>            </div>            <div class="editor-field">                <%= Html.TextBoxFor(Function(model) model.EmployeeName) %>                <%= Html.ValidationMessageFor(Function(model) model.EmployeeName) %>            </div>                        <div class="editor-label">                <%= Html.LabelFor(Function(model) model.EmployeeSalary) %>            </div>            <div class="editor-field">                <%= Html.TextBoxFor(Function(model) model.EmployeeSalary) %>                <%= Html.ValidationMessageFor(Function(model) model.EmployeeSalary) %>            </div>                        <div class="editor-label">                <%= Html.LabelFor(Function(model) model.EmployeeId) %>            </div>            <div class="editor-field">                <%= Html.TextBoxFor(Function(model) model.EmployeeId) %>                <%= Html.ValidationMessageFor(Function(model) model.EmployeeId) %>            </div>                        <div class="editor-label">                <%= Html.LabelFor(Function(model) model.Department) %>            </div>            <div class="editor-field">                <%= Html.TextBoxFor(Function(model) model.Department) %>                <%= Html.ValidationMessageFor(Function(model) model.Department) %>            </div>                        <div class="editor-label">                <%= Html.LabelFor(Function(model) model.Age) %>            </div>            <div class="editor-field">                <%= Html.TextBoxFor(Function(model) model.Age) %>                <%= Html.ValidationMessageFor(Function(model) model.Age) %>            </div>                        <div class="editor-label">                <%= Html.LabelFor(Function(model) model.Skillset) %>            </div>            <div class="editor-field">                <%= Html.TextBoxFor(Function(model) model.Skillset) %>                <%= Html.ValidationMessageFor(Function(model) model.Skillset) %>            </div>                        <div class="editor-label">                <%= Html.LabelFor(Function(model) model.Role) %>            </div>            <div class="editor-field">                <%= Html.TextBoxFor(Function(model) model.Role) %>                <%= Html.ValidationMessageFor(Function(model) model.Role) %>            </div>                        <p>                <input type="submit" value="Create" />            </p>        </fieldset>    <% End Using %>    <div>        <%=Html.ActionLink("Back to Employee List", "Index")%>    </div> </asp:Content>

Conclusion

For developers who are new to ASP.NET Web programming, the MVC Framework approach is very easy to use. MVC Framework application code is also easily maintainable. Developers can also use the Test Driven Development methodology with MVC framework.


   
Tapas Pal is a Microsoft Platform technical professional with Tata Consultancy Services, India. He has with seven years of experience, holds Microsoft certifications in .NET 1.1 and .NET 2.0.
Comment and Contribute

 

 

 

 

 


(Maximum characters: 1200). You have 1200 characters left.

 

 

Sitemap