Sample Project
In the previous section we piece the theories together and tried to understand what is MVC and why we need to learn this programming architecture. So before reading this piece I would recommend you to go through the ASP.NET MVC Introduction Part 1 link for some basic theories. OK, now let's start with building a sample application.
Prerequisites
If you are in VS 2008 you need to download ASP.NET MVC 2. Click here to download release candidate for .NET 3.5 and VS 2008.With VS 2010, it is already shipped and has an automated upgrade wizard that can automatically migrate your existing ASP.NET MVC 1 applications to ASP.NET MVC 2 for you. Also remember MVC 2.0 can be installed side-by-side with ASP.NET MVC 1.0 on the same machine. Ok, let’s get start with. Open your VS IDE 2008 go to File > New Project > ASP.Net MVC give it a name I named it SampleMVC. A dialog box will prompt you to create test projects. If you are a bad programmer skip the test project.
Now have a look at the project structure that created by MVC frame work by default.
The structure of your Project
if you explore the solution that we created there are three main folders – Model, View, and Controller. Views are nothing more than .aspx pages. Other folders here are content folders which can hold resources files, images and Model folder can be represented by entity classes, can be also represented by data table’s data sets etc. This is more related if you are doing data driven based programs. Script file as name indicates can hold JavaScript files. And also you can see another test project if you selected the options for the same while creating project. To create more controller and views right click on the folder and will give you options to create both. So we are created our first ASP.NET application on MVC 2.0 framework!!! Let’s go home! 1. So take the homeController.cs now. In this controller class MVC framework has created 2 new ActionResults by default.One named Index, and one named About. These are nothing more than calling a View titling their names.
2. Inside Index we have a View Data, which is nothing more than a way for a controller to pass data to the view.
3. Inside the view of Index you see that there is that ViewData ["Message"] using the Html.Encode is just a way of accessing the ViewData.
Before that you might be noticed one interesting thing in the web URL something like http://localhost:1744/Home/About . If you have a classic asp.net back ground you might be asking where is the .aspx extension? That is what MVC routing is coming to picture and we already discussed in part1. Ok we are done with the basic stuff. Now let’s come out and think in terms of real time scenarios.See the screen shot for now.
How to do CURD operations?
Now being in this frame work we are going to see that how we can add a view, Model and controller by giving a sample CURD operation.
We will create a sample application which has following things.
- A basic view which has look up values from DB. - EmployeeList.(View1)
- Take the user inputs and save it to DB. - AddEmployee.(View2)
- Read the updated DB and display on EmployeeList.(View1)
To start with we need a data model. But we are not going to worry much on the data model as this framework is going to talk with all most all databases with almost same manner. To take with a simple example I am going to have an employee data model and save and retrieve to an xml file.
In order to add the new view first I am going to add a menu item for my employee view. Go to Site. Master files under shared folder and add this line.
In the Action link we need to specify what action it should take and what the routing values are.
Now we need to handle the action in Controller class, for keeping the modularity we are creating separate controller class called EmployeeController.cs. Microsoft recommends putting your Controller classes underneath the /Controllers directory, (also data model classes underneath your /Models directory, and your view templates underneath your /Views directory).
Let’s go ahead and add our action in it as a method in the controller class and add a view of the same name what we have given for method. Rich MVC template will guide you all these actions. Now we have following classes ready in general.
- EmployeeDataModel.cs - It could be a simple data model.
- EmployeeDAL.cs - This class is to read/ write data model to xml file.
- EmployeeControoler.cs
- EmployeeList.aspx
We are not going to explain the files one and two as it is nothing but having an employee data model and read/write logic to xml file. But See the code in other file:
EmployeeController.cs
public ActionResult AddEmployee()
{
EmployeeDAL empDAL = new EmployeeDAL();
List<string> allRoles = new List<string>();
allRoles = empDAL.GetAllRoles();
EmployeeModel empData = new EmployeeModel();
ViewData["Roles"] = new SelectList(allRoles);
return View(empData);
}
[HttpPost]
public ActionResult Create(EmployeeModel employeeModel)
{
if (ModelState.IsValid)
{
EmployeeDAL empDAL = new EmployeeDAL();
EmployeeModel empData = new EmployeeModel();
empData = (EmployeeModel)ViewData.Model;
EmployeeController controller = new EmployeeController();
empDAL.CreateEmployee();
return RedirectToAction("EmployeeList");
}
else
{
return View("AddEmployee");
}
}
Go ahead and press F5 to display the home page, the new menu item – Employee that we created and on click of Employee it will take you to the new screen. We are going to add the code now to display the employee List Employees below (EmployeeList.aspx):
Now we have a view which read data from model using controller. We are going to add one link button on click of that it should display another view to accept user inputs to add new employee. So go ahead and repeat the same steps and call from a link button on down. Do not forget to add subsequent events in controller class.
And the Add Employee.aspx file look like this:
So how this sample application works?
1. When we are giving http://localhost:2500/Employee/EmployeeList in the address bar the routing engine will look it in global.asax file and for matching our request we have a default routing {controller}/{action}/{id}.So if we receive a URL request of /Employee/EmployeeList, the routing rule will treat " Employee" as the name of the action, and the EmployeeList () method will be invoked to process the request , which will finally load the EmployeeList UI. 2. Now when the user gives new Employee details and click on save. This will call /Employee/Create message or Cretate () method on EmployeeController which will pass view object to data model and redirect the view back to EmployeeList view. Simple right?
So we have some bullet points here:
1. Create Routing and route table to route to controller.
2. Controller does some logics and invokes the message or method where these messages call a view files.
3. Controller says get me a object / model example Employee here, I do whatever I can and pass this to view.
3. Do create your model, it should be an object or ORM model or SQL or whatever. We are not much interested on that.
4. View looks like aspx page but not exactly same. Some people put code behind in view but remember it will break single responsibility principle. Once we add code behind we can do all the non sense there to break the MVC basic rules. Separation of controls is most important concept of MVC.
5. In MVC views job is only to display the data what controller passed.It is not supposed to do any calculations.For example If you want to do tax calculation inside a view..STOP, that is not view job.Do that calculation in controler in pass it back to view.
6. Controller does not know who has called. So this is one of the fundamental for testing frame work. Call your controller from testing and test your controller, model, functionality.
So on successful creation of this sample application I am sure you will be getting ideas on URL Routing basics, creating view/Controller, how to capture a user interaction and how the control updates the model and updates the view back. So now time to look in to test project which is automatically created by MVC framework for you for unit testing. Recommend you to go through the link.