Model View and Controller (MVC) in ASP.Net

What does MVC look like?
MVC

Models encapsulate the objects and data. It consists of all the business logic.

Views generate the user interface, like tables, forms and so on.

Controllers interact with user actions. It takes care of all the magic that happens. It gets the request from the user, gets the information and if required then passes it to the model, lets the model do its thing and then the controller passes it to the view and the view displays the data.

Note

We control the UI of the view. So, based on our logic of HTML, the data is displayed.

All the code is in .cshtml and .cs files.

In MVC we have a precise control of HTML and URLs.

Controller

The Controller is the building block of a MVC project. The Controller is a class present in the System.Web.Mvc namespace.

All the incoming requests are handled by the Controller.

How to create a controller

Step 1

Open Visual Studio and click "New Project...".

visual studio

Step 2

In the installed template, expand Visual C# and then expand Web. Select the Visual Studio 2012 template and then choose ASP.NET MVC 4 web application, give a meaningful name and click OK.

web application

Step 3

Select the project template as empty and view engine as Razor. Click OK.

project template

Step 4

Visual Studio will create a project with minimal layout with auto-generated Models, Views and Controllers directory.

directory

Step 5

In MVC, it is very important to follow the naming convention. By default, every controller name should be suffixed with Controller and must be present inside the Controllers directory.

To add a controller, right-click on the controllers directory then select Add -> Controller.

add a controller

Step 6

Provide controller a name such as HomeController (we will discuss it in just a bit) and scaffolding option template as Empty MVC controller.

controller

In the Solution Explorer, you will see App_Start directory. This directory contains a RouteConfig class that contains the routing configuration that is followed by every MVC application.

RouteConfig
There is a static method RegisterRoutes that contains the routing information.

There are two properties, IgnoreRoute and MapRoute, out of which routes.MapRoute contains the routing information of the application.

  • Name: The name of the route.

  • URL: The format in which the users must type the URL in the address bar of the web browser.

  • Defaults: It is the default routing configuration.

  • Controller: By default, it is Home which means when we run this application it will look for a Home controller but it is customizable.

  • Action: By default, Index is the action method that our HomeController will look for.

  • Id: It is a parameter value that the user may or may not specify. It is optional.

  • For starters this is the reason we named our controller HomeController.

Step 7: Open the HomeController.cs file and repare to work with it.

When we created a HomeController class, it inherits from the controller class that is present in System.Web.Mvc that gives us an Index public method. The action method must be public and all the public methods inside a controller class are termed Action Methods. By default these methods return ActionResult objects.

ActionResult

  1. using System;  
  2. using System.Collections.Generic;  
  3. using System.Linq;  
  4. using System.Web;  
  5. using System.Web.Mvc;  
  6.   
  7. namespace MvcApplication1.Controllers {  
  8.     public class HomeController : Controller {  
  9.         public ActionResult Index() {  
  10.             //to display a content, we can use the content method  
  11.             return Content("This is a content");  
  12.   
  13.             //file download  
  14.             return File(Server.MapPath("~/App_Data/ABC.pdf"), contentType: "application/pdf", fileDownloadName: "A.pdf");  
  15.   
  16.             //to redirect to other action method, use RedirectToAction  
  17.             return RedirectToAction("GetDetails");  
  18.         }  
  19.         public ActionResult GetDetails() {  
  20.             return Content("GetDetails");  
  21.         }  
  22.     }  

We can have different methods with the same name but with different method signatures that we know as method overloading.

So, can we use the same logic here too? Let's look at an example.

  1. public class HomeController : Controller {  
  2.    public string Index() {  
  3.       return "IndexOne output";  
  4.   
  5.    }  
  6.    public string Index(string id) {  
  7.       return id;  
  8.    }  

Now, run the application. We will get an ambiguous error.

ambiguous error

To overcome this issue, we can use the ActionName attribute ActionName.

  1. public class HomeController : Controller {  
  2.    public string Index() {  
  3.       return "IndexOne output";  
  4.   
  5.    }  
  6.    [ActionName("Index_Two")]  
  7.    public string Index(string id) {  
  8.       return "My value " + id;  
  9.    }  

Run the application

When we run our application, MVC will look for the default routeConfig where the controller name is Home and the action method is Index. If the match is found, it will display the content.

Run the application

The ActionName “Index_Two” will be treated as the action method name of the second Index(int id) method.

And if you want to go to the another Index action method, then type the following in the URL.

URL
Press Enter.

index two output
Models

The basic key point you must be familiar with model is that it is just a class file that can hold a simple type or complex type data.

Models can be entities or business objects.

When a user requests a URL, the controller responds to URL request, if required, then it gets data from a model and hands it over to the view. Then the view renders the data and displays the data to the front-end users in HTML format.

DEMO on how to add a Model

Step 1

Open Visual Studio -> select New Project -> expand Installed templates -> expand visual C# -> expand web -> select Visual Studio as template -> select ASP.NET MVC 4 web application as a project -> provide a meaningful name then click OK.

project

Step 2

Select the project template as Empty and view engine as Razor.

Class

Click OK

Step 3

To create a controller class what we did was to go to the Solution Explorer, select the controllers folder, right-click on the controllers folder, add, controller. To add a model we need to do the same thing.

To add a model class, go to the Solution Explorer then select the models folder then right-click on the models folder then select Add -> Class.

creating a Student model

Provide a meaningful name.

Here I will be creating a Student model.

meaningful name

Click Add.

Step 4

Write the following code in the student class.

  1. public class Students {  
  2.     public int StudentId { getset; }  
  3.     public string Name { getset; }  
  4.     public double TotalMarks { getset; }  

Note

The code inside the Student class is nothing more than an auto-implemented property.

So, our model is created.

In real time we retrieve the data from the database using a model. But for here we hardcoded the values in our Controller class.

Step 5

The next step is to add a controller. The reason to add a controller is that without a Controller we won't be able to pass the model data to the view and to pass the data to the view we need a controller.

So, right-click on the Controllers folder then select Add -> Controllers.

Provide the name HomeController and select the scaffolding template as Empty MVC controller.

Click Add.

Step 6

In our Index action method of HomeController, we will create an instance of our student class and pass the value for the properties. But before that there is one thing you must look at carefully.

In the Student model class, you will see that our Student class is present in ModelsDemo.Models and our Controller class is present in the ModelsDemo.Controllers. So, to use the Student class in our Controller class we need to import the ModelsDemo.Models namespace.

  1. using ModelsDemo.Models; 

In our Index action method, write the following code:

  1. using ModelsDemo.Models;  
  2. using System.Web.Mvc;  
  3.   
  4. namespace ModelsDemo.Controllers {  
  5.     public class HomeController : Controller {  
  6.         public ActionResult Index() {  
  7.             Students student = new Students() {  
  8.                 StudentId = 2,  
  9.                 Name = "Max Payne",  
  10.                 TotalMarks = 450.5  
  11.             };  
  12.             return View(student);//pass the object student to the view  
  13.         }  
  14.     }  

Views

Views are nothing more than a HTML file.

It is used to display the requested data for the users. In simple terms, whatever we see as output in a web browser is a view.

Step 7

The final step is to create a view and to create a view all we need to do is right-click on the Index action method and select Add view.

The View name should be Index matching the action name.

The View engine should be Razor (CSHTML).

Select the "Create a strongly-typed view" checkbox and select the model class which is Students.

select the model class

Note

If you don't find the students model class then click the Cancel button and press Ctrl+Shift+B or F6 that will build the project and now again right-click on the Index action method and selected the model class as Students.

Click Add.

Click Add

The reason for creating a strongly typed view is, we will get a compile time error and intellisense. Explains this more in the next article.

Step 8

The next step is to write some HTML code and some C# code that will be rendered and displayed to the front-end user and to do that first write the following codes to create a table.

  1. @model ModelsDemo.Models.Students  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8. <table>  
  9.     <tr>  
  10.         <td><b>Student Id - </b></td>  
  11.         <td></td>  
  12.     </tr>  
  13.   
  14.     <tr>  
  15.         <td><b>Student Name - </b></td>  
  16.         <td></td>  
  17.     </tr>  
  18.   
  19.     <tr>  
  20.         <td><b>Student Marks - </b></td>  
  21.         <td></td>  
  22.     </tr>  
  23. </table> 

So, we have a layout that will display the records. But from where we will get the student records?

In our controller's Index action method we have passed the employee object as a parameter in the View method and we have all created this view as a strongly-typed view and select model class as Students. So, our model for this view is student and all the records are present in this model.

Note

To switch between the HTML and C#, use the @ symbol.

So, we can say:

  1. <tr>  
  2.    <td><b>Student Id - </b></td>  
  3.    <td>@Model.</td>  
  4. </tr> 

HTML

This will give us all the properties present in this model that is nothing but a Student class object.

Note

This model property is a get property that will only return the properties associated within our class object.

property

View codes

  1. @model ModelsDemo.Models.Students  
  2.   
  3. @{  
  4.     ViewBag.Title = "Index";  
  5. }  
  6.   
  7. <h2>Index</h2>  
  8. <table>  
  9.     <tr>  
  10.         <td><b>Student Id - </b></td>  
  11.         <td>@Model.StudentId</td>  
  12.     </tr>  
  13.   
  14.     <tr>  
  15.         <td><b>Student Name - </b></td>  
  16.         <td>@Model.Name</td>  
  17.     </tr>  
  18.   
  19.     <tr>  
  20.         <td><b>Student Marks - </b></td>  
  21.         <td>@Model.TotalMarks</td>  
  22.     </tr>  
  23. </table> 

Build and run the application.

Build

Until then keep learning.

Thank you.


Similar Articles