Creating MVC Project, Database, and Data ModelIn 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)
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 ControllerYour 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
LINQ is used to query business object and find a specific Employee from the Employee List (Model).Using
Function Details(ByVal id As Integer) As ActionResultDim objEditEmployee = (From c In objDatabaseEntities.EmployeeSet Where c.EmployeeId = id Select c).FirstOrDefault() Return View(objEditEmployee)End Function
“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.
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.
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 deleting an employee list, I have only added the Get version and in view added necessary Java Script validating (confirmation message).
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
Creating the ViewsIn 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.
Create Employee<%=""%> <% Using Html.BeginForm()%> <% End Using %><%=Html.ActionLink("Back to Employee List", "Index")%>
ConclusionFor 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.