Controllers in Action

Hello Internet!

As I promised you last time, today we will be talking about Controllers, one of the main components of MVC architecture.

For a better understanding, I will start by a short definition, followed by a small example to concretize the idea behind this concept and finally, we will dive a little deeper to make sure that you are well armed to continue in our ASP.NET MVC journey.

Controllers Definition:

Simply said, Controllers are classes that manage browser requests (from users), retrieve/manipulate model data, and then provide proper rendering output (templates) that hold specific response to the browser (to users).

From this definition, we deduce that controllers are the app’s flow manager since they are concerned with the dispatching of the whole process. Moreover, they work through a cycle that starts from the user request via a given browser and ends up throwing a response in the form of an HTML template that carries the desired answer.


However, in reality the URL talks to a routing mechanism which in turn choose the controller class to instantiate and an action method to call providing its required arguments, but since we have not yet talked about Routers, we will say that the URL is directly connected to an action method in the controller class.

Alright, let’s concretize what we have said so far. In our MVCSchool App (created in my previous post), open the Solution Explorer window and Click on the small arrow to expand the Controllers folder. You will find three default controllers: AccountController.cs, HomeController.cs and ManageController.cs. For now, let’s say that they are responsible for account related requests, home Page, Security And Creating User Role.


Select the HomeController.cs to see the code in it:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace MVCSchool.Controllers
    public class HomeController : Controller
        public ActionResult Index()
            return View();
        public ActionResult About()
            ViewBag.Message = "Your application description page.";
            return View();
        public ActionResult Contact()
            ViewBag.Message = "Your contact page.";
            return View();

As you see, it’s a simple POCO (Plain Old CLR Object) class that extends Controller and has three action methods: Index, About and Contact.

Now, change the phrase in the About method and put what you want.

        public ActionResult About()
            ViewBag.Message = "MVC is gorgeous!";
            return View();

Save and run your app by pressing F5 or Debug -> Start Debugging. Click on the About link or add /Home/About to your browser’s address bar to see your phrase in action.


Awesome! You’ve succeeded to change some text in your application and that’s only the beginning.

Creating a Controller:

After this warm-up, we will do some more advanced changes on your application by adding a new Controller that implements different actions thanks to its methods.

Right-click on the Controllers folder and choose Add -> Controller  Controllers3

Choose “MVC 5 Controller – Empty” option in the Add Scaffold window and press Add button. Then, name your controller LevelController. Controllers4

Visual Studio will add a default index method in your controller to provide the level page with a list of all the levels in your school. Furthermore, it will create a folder named Level in the Views Folder.


As I said before, we will add other controller actions to respond to different URL requests and provide adequate responses. (Controller’s definition)

To show the work of controller actions in more details let’s change the return type of Index() from ActionResult to string and return “Hi, it’s Level.Index(). Do you see me?”, then we will add Browse() and Details() with the same structure as Index().However, each method should return a different message like what you see below:

        // GET: /Level/
        public string Index()
            return "Hi! it's Level.Index(). Do you see me?";
        // GET: /Level/Browse/
        public string Browse()
            return "Hi! it's Level.Browse(). Do you see me?";
        // GET: /Level/Details/
        public string Details()
            return "Hi! it's Level.Details(). Do you see me?";

Save and run you app again. But this time, put the following links in your address bar: localhost:xxxx/Level ; localhost:xxxx/Level/Browse ; localhost:xxxx/Level/Details (xxxx is your port number which differs from one computer to the other)


As you see, each controller action responds to a specific URL with an appropriate message.

Adding Parameters to Controller Actions:

Let’s spice our project up by providing parameters to our methods and see how they respond.

Change the Browse method by adding a string parameter and return a message string like the following:

        public string Browse(string grade)
            string message = HttpUtility.HtmlEncode("Level.Browse, Grade = " + grade);
            return message;

Here, I’ve used HttpUtiliy.HtmlEncode() method to protect our code from any hacking injection such as http://localhost:xxxx/Level/Browse?Genre=<script>window.location=’’</script>.

Now, browse to “localhost:xxxx/Level/Browse?Grade=6thGrade” to let your action method read/use arguments you provided in the URL:


OK, there is something else to say about parameters. According to ASP.NET MVC’s default routing conventions, you can directly pass the URL segment to your method as a parameter if and only if your method’s parameter is named “ID”.

For example, if you add an int parameter named ID to the Details() method like in the following code:

        // GET: /Level/Details/
        public string Details(int id)
            string message = "Level.Details, ID = " + id;
            return message;

You will no longer need to provide any parameter in the URL as we saw previously. Hence, My Id number will be directly embedded in the URL: “localhost:xxxx/Level/Details/9”


Of course, we didn’t cover everything yet because in real life scenarios you will not use controllers alone. In my future posts, we’ll talk more plainly about Views, Models and how this trio work homogeneously together to produce well designed, scalable and maintainable applications. However, for the sake of learning the basics, we have gone through these steps and I hope that by now you know more or less how controllers work.

In my next tutorial, I will be dealing with views and how they work. Till then, take good care and don’t forget to try out multiple times what we saw up to now.

Goodbye internet!


Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s

Powered by

Up ↑

%d bloggers like this: