Practical Approach to Learn MVC: Part 1

Introduction

This article explains MVC in ASP.Net. I will only show the practical (programmatic) approach of learning ASP.Net MVC. In this article I am not paying much attention to the theory.

The first question is, what is ASP.Net MVC?

“The Model-View-Controller (MVC) architectural pattern separates an application into three main components: the model, the view and the controller. The ASP.NET MVC framework provides an alternative to the ASP.NET Web Forms pattern for creating Web applications.” Microsoft



The image above shows the graphical representation of the MVC architecture. For more information click here.

Installing MVC in our machine

Before installation we first need to check which version of MVC is already installed in our machine because if you install Visual Studio then some version of MVC is already installed. To determine the version of MVC installed on your machine use the following procedure.

Go to "Control Panel" then click on "Programs and Features" then scroll and search Microsoft MVC. I hope you get something like the following image.



That indicates that only MVC 2 has been installed on that machine. Click the following links to download and install MVC4 and MVC5 templates.

Click here to download MVC4
Click here to download MVC5

Create MY First MVC application

Open Visual Studio (in this example I am working with Visual Studio 2013) then go to the New Project under the web tab then select ASP.NET MVC 4 web application. Provide a proper name and click OK.



After clicking OK the following window appears.



Select Empty template and view engine as Razor. Razor is preferred by most MVC developers. We will discuss the Razor View Engine in detail in a later part of this tutorial. By default there are two view engines, ASPX and Razor, supported by MVC. If you want you can install other view engines also and use those engines.

Now click on Ok. Then our project solution will look as in the following:



As our solution is showing there are three main folders, Models, Views and Controllers. The MVC architecture is based on this folder. The Views contains the UI code that we need to show to our end user.

The controller is supposed to be the handler that executes the view request depending on the needs of the user.

The Models folder contains mainly the code that communicates the database or other services.

Our solution is now ready. We will create our first MVC application. This application will just show the static message with the version of MVC we are using.

Right-click on the Controllers folder then click on Add => Controller then the following window appears. Provide the proper controller name, say “Home”. Select Empty MVC Controller. Click on OK.



Don't worry about the other the things, we will discuss them in future sessions. The following code will be generated automatically:

  1. namespace MvcApplication1.Controllers  
  2. {  
  3.     public class HomeController : Controller  
  4.     {  
  5.         //  
  6.         // GET: /Home/  
  7.   
  8.         public ActionResult Index()  
  9.         {  
  10.             return View();  
  11.         }
  12.     }  

In the code above MvcApplication1 is the name of the application. Controllers is the Controllers folder name so it is the namespace for HomeController.

Remember: In ASP.Net the MVC controllers name must end with Controller otherwise you will get an error.

A controller inherited from the Controller class with is indirectly implementing the IController interface.

Change the return type of the Index method to string.

  1. public string Index()  
  2. {  
  3.     return "This is my First mvc application.";  

We will discuss ActionResult and View() letter. Now run the application. That's it, our first MVC application is ready. We get the following output. It's so simple.


Now you must be wondering how we get this output. How our web server knows which page to execute and so on. In the preceding output screen you are only seeing http://localhost:3247. It is showing the type:

http://localhost:3247/Home/Index

This is where you will get the same output. Now it's a bit more clear how our web server knows which method to execute.

The reason is by default the Home controller and Index method has been called in MVC. We can change it. How?

Here the MVC URL mapping comes into picture. Now the question is, where is URL mapping defined? Go to Global.asax where you will get the following line inside Application_Start():

RouteConfig.RegisterRoutes(RouteTable.Routes);

Right-click on RegisterRoutes then go to the definition. You will then get the following method.

  1. public static void RegisterRoutes(RouteCollection routes)  
  2. {  
  3.     routes.IgnoreRoute("{resource}.axd/{*pathInfo}");  
  4.   
  5.     routes.MapRoute(  
  6.         name: "Default",  
  7.         url: "{controller}/{action}/{id}",  
  8.         defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }  
  9.     );  

Ignore the first line and look at the others.

Here in the default section controller = "Home", action = "Index", id = UrlParameter.Optional The controller name is Home and the action method is Index. Change it to whatever you want then that page will display instead of Home. The URL does not have an id. This is not a problem because id is optional in the default route. We can read the id using the following code:

  1. public string Index(string id)  
  2. {  
  3.     return "The id = "+id;  

When we run that code we need to use the following kind of URL to pass the id:

http://localhost:3247/Home/Index/10

Now again the question is, can we pass multiple values with the URL?

And the answer is yes, just change the Index method as in the following:

  1. public string Index(string id,string name)  
  2. {  
  3.     return "The id = "+id +" Name "+name;  

Note: The name of the URL parameter must match the function parameter.

Now run the application and use the following URL to get your output:

http://localhost:3247/Home/Index/10?name=Manish

You will get your output. We can also use Request.QueryString["name"]; to read the URL query string as we did in our conventional ASP.Net application.

That's it for today. The rest of this session we will learn in my future articles.

Practical Approach to Learn MVC: Part 6

Summary

In this illustration you came to understand the basics of MVC.


Similar Articles