Learn MVC (Model view controller) Step by Step in 7 days - Day 1


So, what's the agenda?

As the article name says learn MVC, so the agenda is simple; we are going to learn ASP.NET MVC in 7 days.

The way we will learn MVC in this series of articles is by doing Labs, looking at detailed steps of how to achieve those labs and also looking at demonstration videos.

MVC1.jpg

This complete article is divided into 7 days with 42 hands-on labs and every day we will do 6 labs to help us learn.

So get ready for day 1. For day 1 the following is our agenda; we will start with an introduction, do a simple hello world and finally in the 6th lab we will create a simple customer data entry screen using HTML helper classes.


Lab No. Lab description YouTube Video demonstration for the same
1 Introduction Why MVC? NA.
2 A simple Hello world ASP.NET MVC application. http://youtu.be/KAKxm4eQP24?hd=1
3 In this Lab we will see how we can share data between controller and the view using view data. http://youtu.be/Fu9v2MIDlTA?hd=1
4 In this lab we will create a simple customer model, flourish the same with some data and display the same in a view. http://youtu.be/0-UdqWy9lVc?hd=1
5 In this lab we will create a simple customer data entry screen with some validation on the view. http://youtu.be/1dlxtHuRw34?hd=1
6 This Lab will demonstrate how to expedite your MVC development process using HTML helper classes. Pending...

You can watch my .NET interview questions and answers videos on various sections like WCF, Silver light, LINQ, WPF, Design patterns, Entity framework etc.

So why MVC when ASP.Net code-behind was so good?


I am sure all ASP.NET developers love the code-behind concept. Accepting something new like MVC will not convince them. So let's analyze the problems with the current code-behind stuff.

When we generally talk about ASP.NET applications built on a tiered architecture they are divided into four parts, the UI (ASPX pages), code-behind (ASPX.CS pages), the middle tier (.NET classes) and finally the Data Layer.

If you see from the aspect of code distribution there is a major amount of with logic in the middle tier or in the code-behind (APX.CS files). The UI or ASPX files are HTML files which is more of UI design and data access logic is pretty much standard components like enterprise data blocks, entity data contexts etc.

 MVC2.jpg

Let's try to analyze the problems.

Problem number 1:- UNIT Testing

From the aspect of unit testing we can exclude the data logic and the UI HTML. The data logic classes are already time tested components like enterprise data block, entity data context or LINQ data context. So we really do not have to put much effort into testing the DAL separately. In case you have a custom data access layer it will still be easy to test them as they are simple .NET classes.

There is no logic in testing ASPX HTML since it's more of look and feel.

The middle tier is again a simple .NET class like data logic so you can easily do unit testing using VSTS or NUNIT.

Now comes the most important one; the code-behind. The code-behind is filled with action and testing them is one of the most important things to be done. The only way to invoke the code is by doing manual testing. From a longer perspective this would not be a great choice.

Even though http://www.microsoft.com/ has always boasted about how the ASP.NET code-behind is separate from the UI, in practical sense it's very difficult to decouple ASP.NET code-behind and do unit testing on them.

The ASP.NET code-behind is intimately tied to an ASP.NET Httpcontext object which makes unit testing very difficult.
Just think; how do I unit test the following ASP.NET code. How do I create a Http context object, how do I simulate the sender and eventargs objects of the button clicks etc.

FYI: - Many developers would talk about mock testing, rhino mocks etc. but still it's cryptic and the complication increases with session variables, view data objects, ASP.NET UI controls creating further confusion.

3.JPG

Problem 2 :- The reality of separation of code and UI


As said previously the ASPX and the ASPX.CS cannot be decoupled in reality thus reducing reusability. Yes, Microsoft did at first say that the code-behind is separate from the UI but then they are probably separate physical files only and one cannot just exist without the other.

For instance let's say the same button click is code that when called via HTTP POST should display using displayinvoice.aspx and when called via HTTP GET should display in TreeView. In other words we would like to reuse the code-behind. Just think of how we can do that using the current code-behind techniques.

4.JPG

Our HERO MVC (Model, view and controller)


That's where MVC comes to rescue. The code-behind is moved to a simple .NET class called a controller. Any user request first comes to the controller class; the controller class then invokes the model and attaches the model to the view for display to the end user.

5.JPG

As this controller class is a simple .NET class we can reuse and also do unit testing easily. So let's see how we can create a MVC application using MVC template provided by Visual Studio.

Pre-requisite for MVC


Before we start the day lets ensure that you have all the ingredients to create a MVC application.
  • Visual Studio 2010 or the free Visual Web Developer 2010 Express. These includes ASP.NET MVC 2 template by default.
  • Visual Studio 2008 SP1 (any edition) or the free Visual Web Developer 2008 Express with SP1. These do not include ASP.NET MVC 2 by default; you must also download and install ASP.NET MVC 2 from http://www.asp.net/mvc/.
So once you have all your pre-requisites its time to start with the first lab.

Lab1:- Creating a simple hello world ASP.NET MVC Application

In this lab we will create a simple hello world program using MVC template. So we will create a simple controller, attach the controller to simple index.aspx page and view the display on the browser.

Video demonstration for Lab 1


In case you want to spend more time with your family rather than reading the complete article you can watch the following 5 minute YouTube video.

V1.JPG

Step1:- Create project

Create a new project by selecting the MVC 2 empty web application template as shown in the following figure.

6.JPG

Once you click ok, you have a readymade structure with appropriate folders where you can add controllers, models and views.

7.JPG

Step 2:- Add controller


So let's go ahead and add a new controller as shown in the following figure.

8.JPG

Once you add the new controller you should see some kind of code snippet as shown in the following snippet.
public class Default1Controller : Controller
{
//
// GET: /Default1/
public ActionResult Index()
{
return View();
}
}

Step 3:- Add View

Now that we have the controller we need to go and add the view. So click on the Index function which is present in the control and click on add view menu as shown in the following figure.

9.JPG

The add view pops up a modal box to enter view name which will be invoked when this controller is called as shown in the figure below. For now keep the view name the same as the controller name and also uncheck the master page check box.


10.JPG

Once you click on the ok button of the view, you should see a simple ASPX page with the following HTML code snippet. In the following HTML code snippet I have added "This is my first MVC application".
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Index</title>
</head>
<body>
<div>
This is my first MVC application
</div>
</body>
</html>

Step 4:- Run the application

If you do a CNTRL + F5 you should see an error as shown in the following figure. This error is obvious because we have not invoked the appropriate controller / action.

11.JPG

If you append the proper controller on the URL you should be able to see the proper view.


12.JPG

So what's in the next Lab?


Now that we have created a simple MVC hello world, it's time to see how we can pass data from controllers to views. The first hit comes to the controller which will load your business objects or model and you would like to transfer these objects to the view to display them.

Lab2:- Passing data between controllers and views


The controller gets the first hit and loads the model. Most of the time we would like to pass the model to the view for display purpose.

As an ASP.NET developer your choice would be to use session variables, view state or some other ASP.NET session management object.

The problem with using an ASP.NET session or view state object is the scope. ASP.NET session objects have session scope and view state has page scope. For MVC we would like to see scope limited to controller and the view. In other words we would like to maintain data when the hit comes to controller and reaches the view and after that the scope of the data should expire.

That's where the new session management technique has been introduced in ASP.NET MVC framework i.e. ViewData.

13.JPG

Video demonstration for Lab 2


The following is a simple YouTube video which demonstrates the lab for view data. In this video we will see how we can share data between controller and the view using view data. So we will create a simple controller, record the current data in a view data variable and then display the same in the view using the percentage tag.

Step1:- Create project and set view data


So the first step is to create a project and a controller. In the controller, set the ViewData variable as shown in the following code snippet and kick off the view.
public class DisplayTimeController : Controller
{
//
// GET: /DisplayTime/

public ActionResult Index()
{
ViewData["CurrentTime"] = DateTime.Now.ToString();
return View();
}

}

Step 2:- Display view data in the view.

The next thing is to display data in the view by using the percentage tag. One important point to note is the view does not have a code-behind. So to display the view we need to use the <%: tag in the aspx page as shown in the following code snippet.

<body>
<div>
<%: ViewData["CurrentTime"] %>
</div>
</body>

So what's in the next Lab?

So now that we know how to pass data using view data, the next lab is to create a simple model and see all the 3 MVC entities (i.e. model, view and controller) in action.

Lab 3:- Creating a simple model using MVC

In this lab we will create a simple customer model, fill it with some data and display it in a view.

Video demonstration for Lab 3

The following is a video demonstration of that.

V2.JPG

Step1:- Create a simple class file


The first step is to create a simple customer model which is nothing but a class with the 3 properties code, name and amount. Create a simple MVC project, right-click on the model folder and click on add new item as shown in the following figure.

14.JPG

From the templates select a simple class and name it customer.
15.JPG

Create the class with 3 properties as shown in the following code snippet.
public class Customer
{
private string _Code;
private string _Name;
private double _Amount;

public string Code
{
set
{
_Code = value;
}
get
{
return _Code;
}
}

public string Name
{
get
{
return _Name;
}
set
{
_Name = value;
}
}

public double Amount
{
set
{
_Amount = value;
}
get
{
return _Amount;
}
}
}

Step2:- Define the controller with action

The next step is to add the controller and create a simple action display customer as shown in the following code snippet. Import the model namespace in the controller class. In the action we created the object of the customer class, filled it with data and passed it to a view named "DisplayCustomer".
public class CustomerController : Controller
{
.....
....
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = 12;
objCustomer.CustomerCode = "1001";
objCustomer.Amount = 90.34;

return View("DisplayCustomer",objCustomer);
}
}

Step3:- Create strongly typed view using the class

We need to now join the points of MVC by creating views. So right-click on the view folder and click add view. You should see a drop down as shown in the following figure. Give a view name, check create a strongly typed view and bind this view to the customer class using the dropdown as shown in the following figure.

16.JPG

The advantage of creating a strong typed view is you can now get the properties of class in the view by typing the model and "." as shown in the following figure.

17.JPG

The following is the view code which displays the customer property value. We have also put an if condition which displays the customer as privileged customer if above 100 and normal customer if below 100.
<body>
<div>
The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>
This is a priveleged customer
<% } else{ %>
This is a normal customer
<%} %>

</div>
</body>

Step 4 :- Run your application

Now the "D" thing, hit Cntrl + F5 and pat yourself for one more lab success.

18.JPG

So what's in the next Lab?

In this sample we filled the customer object from within the controller; in the next lab we will take data from an input view and display it. In other words we will see how to create data entry screens for accepting data from views.

Lab 4:- Creating simple MVC data entry screen

Every project whetehr small or big needs data entry screens. In this lab we will create a simple customer data entry screen as shown in the following figure using a MVC template.

19.JPG
As soon as the end user enters details and submits data it redirects to a screen as shown below. If he entered an amount less than 100 it displays as a normal customer else it displays as a privileged customer.

20.JPG

Video demonstration for Lab 4

The following is a simple video demonstration for this lab.

V3.JPG

Step1:- Creating your data entry ASPX page

The first step is to create the data entry page using the simple HTML form action tag as shown in the following code snippet. The most important point to note in the following code snippet is that the action is pointing to the controller action i.e 'DisplayCustomer'.
<form action="DisplayCustomer" method="post">
Enter customer id :- <input type="text" name="Id" /> <br />
Enter customer code :- <input type="text" name="CustomerCode" /><br />
Enter customer Amount :-<input type="text" name="Amount" /><br />
<input type="submit" value="Submit customer data" />
</form>

Step2:- Creating the controller

The above defined form action will post to the controller class and on the function "DisplayCustomer". So we need to get the data from the HTML controls, fill the object and send the object to the view.

The following is the code snippet of displaycustomer which fills the customer object by collecting data from request.form and sends the object to the view displaycustomer.

public class CustomerController : Controller
{
.....
.....
[HttpPost]
public ViewResult DisplayCustomer()
{
Customer objCustomer = new Customer();
objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());
objCustomer.CustomerCode = Request.Form["Id"].ToString();
objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ;
return View("DisplayCustomer", objCustomer);
}
}

Step3:- Create the view to display the customer object

The next step is to create the "DisplayCustomer" view. So right-click on the view folder and click add view. You should see a drop down as shown in the following figure. Give a view name, check create a strongly typed view and bind this view to the customer class using the dropdown as shown in the following figure.

21.JPG

The advantage of creating a strong typed view is you can now get the properties of a class in the view by typing the model and "." as shown in the following figure.

22.JPG

The following is the view code which displays the customer property value. We have also put an if condition which displays the customer as privileged customer if above 100 and normal customer if below 100.
<body>
<div>
The customer id is <%= Model.Id %> <br />

The customer Code is <%= Model.CustomerCode %> <br />

<% if (Model.Amount > 100) {%>
This is a priveleged customer
<% } else{ %>
This is a normal customer
<%} %>

</div>
</body>

Step 4:- Finally run the project

Final step is to run the project and see the output.

23.JPG

You should be also able to test above 100 and below 100 scenarios.

24.JPG

So what's in the next Lab?
In this lab we created a simple data entry screen which helped us fill the customer object. This customer object was then passed to the view for display.

If you closely watch the current lab we have done a lot of coding i.e. creating the HTML screens, flourishing the object etc. It would be great if there was some kind of automation. In the next lab we see how HTML helper classes help to minimize many of these manual coding and thus increase productivity.

Lab 5:- using HTML helper to create views faster

In our previous lab we created a simple customer data entry screen. We completed the lab successfully but with two big problems:-

  • The complete HTML code was written manually. In other words, less productive. It's like going back to dark ages where developers used to write HTML tags in Notepad.

    <form action="DisplayCustomer" method="post">
    Enter customer id :- <input type="text" name="Id" /> <br />
    Enter customer code :- <input type="text" name="CustomerCode" /><br />
    Enter customer Amount :-<input type="text" name="Amount" /><br />
    <input type="submit" value="Submit customer data" />
    </form>

  • Added to it lot of manual code was also written in the controller to fill the object and send data to the MVC view.

    public class CustomerController : Controller
    {
    .....
    .....
    [HttpPost]
    public ViewResult DisplayCustomer()
    {
    Customer objCustomer = new Customer();
    objCustomer.Id = Convert.ToInt16(Request.Form["Id"].ToString());
    objCustomer.CustomerCode = Request.Form["Id"].ToString();
    objCustomer.Amount = Convert.ToDouble(Request.Form["Amount"].ToString()); ;
    return View("DisplayCustomer", objCustomer);
    }
    }

In this lab we will see how to use MVC HTML helper classes to minimize the above manual code and increase productivity.

Step 1:- Create the Customer class

Create a simple customer class; please refer to Lab 5 for the same.

Step2:- Creating the input HTML form using helper classes

HTML helper classes have ready-made functions by which you can create HTML controls with ease. Go to any MVC view and see the intellisense for HTML a helper class; you should see something as shown in the following figure.

25.JPG

By using HTML helper class you can create any HTML control like textbox, labels, list box etc just by invoking the appropriate function.

In order to create the form tag for HTML we need to use "Html.BeginForm"; the following is the code snippet for that.
<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post)) 
{%>
-- HTML input fields will go here
<%} %>

The above code will generate the following HTML:
<form action="DisplayCustomer" method="post">
.....
.....
</form>

The HTML helper "beginform" takes three input parameters action name (Method inside the controller), controller name (actual controller name) and HTTP
posting methodology (Post or GET).

26.JPG

If you want to create a text box, simply use the "TextBox" function of the HTML helper class as shown in the following code. In this way you can create any HTML controls using the HTML helper class functions.
Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />

The above code snippet will generate the following HTML code.
Enter customer id :- <input type="text" name="Id" /> <br />

To create a data entry screen like the one shown below we need to use the following code snippet:

27.JPG

<% using (Html.BeginForm("DisplayCustomer","Customer",FormMethod.Post))
{ %>
Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />
Enter customer code :- <%= Html.TextBox("CustomerCode",Model) %><br />
Enter customer Amount :- <%= Html.TextBox("Amount",Model) %><br />
<input type="submit" value="Submit customer data" />
<%} %>

Step 3:- Create a strong typed view by using the customer class

So once you have created the view using the HTML helper classes it's time to attach the customer class with the view; please refer to lab 5 for that.

Step4:- Creating the controller class.

The final thing is the controller code. The controller code now becomes very simple. The customer object will be automatically filled as we have used the HTML helper classes. You will create the controller class as we did in Lab 4 but we do not need to write any kind of code for connecting the HTML screens with the controller, it's all hidden and automated.
[HttpPost]
public ActionResult DisplayCustomer(Customer obj)
{
return View(obj);
}

Enjoy your output for different conditions of customer amount entered.

28.JPG

So have a toast of beer for completing your first day of MVC labs.


29.JPG

What's for the second day?


In the second day we will talk about URL routing, ease of MVC unit testing, MVC Controller attributes and lot more. The next lab will bit more advanced as compared to the first day. Following is the link for the second day of MVC (Model view controller) Step by Step.


Similar Articles