MVC 2 is quiet old and this article was written long years back. We would recommend you to start reading from our fresh Learn MVC 5 step by step series from here :- http://www.codeproject.com/Articles/866143/Learn-MVC-step-by-step-in-days-Day
Contents
Just a quick word on both the author’s. Both Shivprasad Koirala and Sukesh Marla are professional MVC trainers you catch them every Saturday and Sunday in Andheri Mumbai where they teach MVC on a weekly basis
As the article name says, learn MVC; so the agenda is simple, we are going to learn ASP.NET MVC in 7 days.
For the first day we will start with a a simple Hello World,passing data between controllers and views , HTML helper classes , MVC models and we will also create a simple customer data entry page.
Lot of developers think that ASP.NET is different and MVC is different. But actually they are the same.
ASP.NET is a web framework of Microsoft and MVC is a visual studio code template to write code using MVC architecture style. The proper name of OLD ASP.NET is “ASP.NET webforms”. So ASP.NET webform is the old ASP.NET with behind code and MVC is the new thing. But both of them use ASP.NET framework.
So let us this straight ASP.NET is a framework while MVC and Webform are coding styles. MVC is the new thing and WebForm is your old code behind style.
So why MVC and why is better than Webforms?
As a ASP.NET Webform developer you will miss lot of your favorites in MVC. In MVC there No behind code , No rad server controls , No ViewState , No ASP,NET Page Life cycle and many more. So in the initial stages you will truely struggle to believe that MVC is better than Webforms. So my suggestion is to go through the below 30 minutes of the video to understand why MVC stands out better than Webform.
Pre-requisite for MVC
Before we start the day let's ensure that you have all the ingredients to create an MVC application. Now MVC has lot of versions MVC 2 , MVC 3 , MVC 4 and MVC 5. So depending on which version you are working you need the appropriate visual studio version.
- If you are doing MVC 5 you need VS 2013 you can download the same from http://www.visualstudio.com/en-us/products/visual-studio-express-vs.aspx
- If you are doing MVC 3 and 4 you need VS 2012. http://www.microsoft.com/en-us/download/details.aspx?id=34673
- For MVC 2 you need VS 2010 2008 will also do.
So once you have all your pre-requisites it is time to start the first lab.
Lab 1: Creating a simple Hello World ASP.NET MVC application
In this lab we will create a simple Hello World program using an MVC template. We will create a simple controller, attach the controller to a simple index.aspx page, and view the display on the browser.
You can also watch the below MVC 5 video which shows how to display a simple "HelloWorld" in MVC 5.
Open Visual studio 2013 , click on file --> new project. Expand Visual C# node , click on Web and click on ASP.WEB Application template , give name and folder path and press ok.
One of the biggest development in MVC 5 is one ASP.NET. If you look prior to visual studio 2013 i.e. in VS 2012 and below once you choose a coding template like MVC or Webforms you are stuck to it. You can't mix both of them in VS 2012. So if you start a project with MVC coding style you cannot use webforms and also vice-versa if you start with webforms you can't use MVC.
In case you are curious to see VS 2012 structure you can see the same in VS 2013 by clicking on "Visual studio 2012" menu as shown in the IDE. You can see how we have different templates like MVC , WebApplication etc. Once you start with MVC you are stuck with it or once you start with Webforms you are stuck with the same.
And also if you see logically WebForm ,MVC and WebAPI use ASP.NET framework internally. So having different templates has lead to lot of confusion among developers. Many developers have started thinking ASP.NET is different than MVC read this ASP.NET and MVC confusion.
So in VS 2013 they have combined all the templates in one ASP.NET template i.e. "ASP.NET Web Application" to avoid confusion and also you can get same experience either as a webform developer or MVC developer. So if you start using MVC you still have options of creating a view using Webform ASPX views.
So when you click on "ASP.NET Web application" you will see all the templates under one umbrella as shown below.
So do the following: -
Step 1: - Select MVC template and also the MVC check box. Most probably the checkbox will get disabled if you select the MVC template.
Step 2: - Click Change Authentication and set it to "No Authentication". As this is our first MVC project we do not want to get involved in to Authentication and Authorization. In Day 3 we are going to cover Authentication in more details.
One of the benefits of MVC is "Unit" test. Because you do not have behind code and controllers have become simple classes you can unit test controllers very easily.But for now we will keep this option unselected as our main intention is to display hello world.
Let's spend some time in understanding the solution created. The first thing you will notice is that there are lot of folders created, see the below figure.
The most important from these folders is the "View" , "Model" and "Controllers" folder. MVC architecture is divided in to three sections model, view and controller.
So the first hit comes to the controller , he creates the object of model and view and sends the final response to the end user.
Folder Name | Description |
View | In this folder you will add MVC views which can be HTML , Razor or Webform pages. |
Model | In this folder you will add model classes. Models are simple .NET classes which provides data and probably also contain validations. So in this folder you will add Customer class, Supplier class etc. |
Controller | In this folder you will add controller and controllers can have actions. This guy is responsible for taking the request from the end user, invoking the appropriate actions, creating object of the model and then tieing up the view and model together to send the results as response. |
Other folders |
Script | Here you add your javascript files. You will find Jquery and angular javascript files by default as they are included by visual studio itself. |
App_Start | Before the MVC application comes live it need lot of objects to be activated and initialized. For example routing , bundling and minification components etc. You do not need to worry about this folder at this moment we will be discussing about each objects later. For example routing is explained in MVC day 2 , bundling is explained in Day 5 and so on. So relax and do not think about this folder at this moment. |
Content | This folder has CSS(Cascading style sheet) which gives a uniform look and feel for your project. |
App_Data | App_Data is for file based data store. Normally developers use RDBMS like SQL Server, oracle etc but some time people use XML, txt files to store data. So this folder is created when you store data in files. |
Fonts | In case you fonts which you are using in your web application you can put them here. |
The next step is to add the controller. Go to the controllers folder , right on click and click the controller menu as shown in the below figure.
The next screen which comes up is to select "Scaffold" templates. Scaffolding is a technique in which the MVC template helps to auto-generate CRUD code. CRUD stands for create, read, update and delete.
But at this moment we are learning MVC so selecting Scaffolding or readymade code is not a good option. So select MVC 5 Controller empty option as shown in the below figure.
Give a name to the controller like "FirstMVCController". But do not delete the word controller. "Controller" at the end is a kind of necessary thing. So do not delete this word.
Once the controller class is created as shown in the below figure. Add a action to it "SayHello" as shown in the below figure. One controller can have multiple actions. So a "Home" controller can have actions like "GotoHome", "GotoIndex" etc.
public class FirstMVCController : Controller
{
//
// GET: /FirstMVC/
public ActionResult SayHello()
{
return View();
}
}
So we have created the controller and the action. But when the end user request's the controller and action we need to invoke a view. For now we will not be talking about model to keep this "HelloWord" MVC example simple.
Now in your folders section you should see a folder created with the name of the controller i.e. "FirstMVC" as shown below.
Right click on the "FirstMVC" folder and add a view.
Give a nice name , do not choose any kind of template for now as we want to keep it simple so select the "Empty (withoutmodel)".
View is a simple Razor HTML page. In the body just type something like as we have done in the below code.
<body>
This is my first MVC program.
</body>
So the view is created and controllers are created. It's time to connect the view with the controller. So in the "SayHello" action in the view type your view name as shown in the below code.
public ActionResult SayHello()
{
return View("HelloView");
}
Once you are all set its time to enjoy the output of your first program. Hit Control key + F5 and type in the below URL after the localhost port. The way the URL should be typed is as follows: -
Localhost:portnumer/ControllerName/ActionName
Please note the controller name should be typed without the word controller as shown in the below image.
Now relax for 30 seconds and enjoy your first program. Congrats to make it till here.
In case you are getting the below common error do not panic you need to check something more.
So first let’s try to understand what the error says. The error says that the view i.e. "HelloView" view should either be in a shared folder or in the controller name folder. For instance in our case the controller name is “FirstMVC” so either you move your view in to “FirstMVC” folder or you move it to the “shared” folder as shown in the below figure.
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 the controllers to the 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.
Lab 2: 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 purposes. 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 the 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 the scope limited to the controller and the view. In other words we would like to maintain data when the hit comes to the 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 the ASP.NET MVC framework, i.e., ViewData.
Video demonstration for lab 2
Below is a simple YouTube video which demonstrates the lab for the view data. In this video we will see how we can share data between the 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: http://youtu.be/Fu9v2MIDlTA?hd=1.
Step 1: 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 below code snippet and kick off the view.
public class DisplayTimeController : Controller
{
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 below 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 three 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, flourish it with some data, and display it in a view.
Video demonstration for Lab 3
Below is a video demonstration: http://youtu.be/0-UdqWy9lVc?hd=1.
Step 1: Create a simple class file
The first step is to create a simple customer model which is nothing but a class with three 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 below figure.
From the templates, select a simple class and name it as Customer
.
Create the class with three properties as shown in the below code snippet.
public class Customer
{
private string _Code;
private int _Id;
private double _Amount;
public string CustomerCode
{
set
{
_Code = value;
}
get
{
return _Code;
}
}
public int Id
{
get
{
return _Id;
}
set
{
_Id= value;
}
}
public double Amount
{
set
{
_Amount = value;
}
get
{
return _Amount;
}
}
}
Step 2: Define the controller with action
The next step is to add the controller and create a simple action display customer as shown in the below code snippet. Import the model namespace in the controller class. In the action, we create an object of the customer class, flourish with some data, and pass 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);
}
}
Step 3: 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 dropdown as shown in the below 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 below figure.
Note :- In case you are not able to see the model in the drop down , please compile your project once.
The advantage of creating a strong typed view is you can now get the properties of the class in the view by typing the model and “.” as shown in the below figure.
Below is the view code which displays the customer property value. We have also put an if
condition which displays the customer as a privileged customer if above 100 and a 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 Ctrl + F5 and pat yourself for one more lab success.
So what’s in the next lab?
In this sample we flourished 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 a simple MVC data entry screen
Every project small or big needs data entry screens. In this lab we will create a simple customer data entry screen as shown in the below figure using an MVC template.
As soon as the end user enters details and submits data it redirects to a screen as shown below. If the entered amount is less than 100 it displays normal customer, else it displays privileged customer.
Video demonstration for lab 4
Here is a simple video demonstration for this lab: http://youtu.be/1dlxtHuRw34?hd=1.
Step 1: 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 below code snippet. The most important point to note in the below 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>
Step 2: 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, flourish the object, and send the object to the view.
Below is the code snippet of DisplayCustomer
which flourishes 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);
}
}
Step 3: 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 dropdown as shown in the below 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 below figure.
The advantage of creating a strong typed view is you can now get the properties of the class in the view by typing the model and “.” as shown in the below figure.
Below is the view code which displays the customer property value. We have also put an if
condition which displays the customer as a 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
The final step is to run the project and see the output.
You should also be able to test above 100 and below 100 scenarios.
So what’s in the next lab?
In this lab we created a simple data entry screen which helped us flourish 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 HTMLHelper 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:
<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>
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);
}
}
- The complete HTML code was written manually. In other words, it was less productive. It’s like going back to the dark ages where developers used to write HTML tags in Notepad.
- Added to that, a lot of manual code was also written in the controller to flourish the object and send data to the MVC view.
In this lab we will see how to use MVC HTMLHelper classes to minimize manual coding and increase productivity.
Step 1: Create the Customer class
Create a simple customer class, please refer to Lab 5 for details.
Step 2: Creating the input HTML form using helper classes
HTML helper classes have readymade functions by which you can create HTML controls with ease. Go to any MVC view and see the intellisense for the HTMLHelper class, and you should see something as shown in the below figure.
By using the HTMLHelper class you can create any HTML control like TextBox
, Label
, ListBox
, etc., just by invoking the appropriate function.
In order to create the form
tag for HTML we need to use “Html.BeginForm
”. Shown below 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 below 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).
If you want to create a text box, simply use the “TextBox
” function of the HTMLHelper class as shown in the below code. This way you can create HTML controls using the HTMLHelper class functions.
Enter customer id :- <%= Html.TextBox("Id",Model)%> <br />
The above code snippet will generate the below 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 the use the below code snippet.
<% 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 HTMLHelper classes it’s time to attach the customer class with the view; please refer to lab 5 for details.
Step 4: Creating the controller class
The final thing is the controller code. The controller code now becomes very simple. The customer object will be auto flourished 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 amounts entered.
So have a toast of beer for completing your first day of MVC labs.
What’s for the second day?
In the second session, we will talk about URL routing, ease of MVC unit testing, MVC Controller attributes, and a lot more. The next lab will be a bit more advanced as compared to the first day. Below is the link for the second day: Click here for the day second MVC step by step.
Below are further link which you can explore to learn MVC
Start with MVC 5
In case you want to start with MVC 5 start with the below video Learn MVC 5 in 2 days.
For further reading do watch the below interview preparation videos and step by step video series.