MVC Part Two (Controllers and Basic Concepts)

This is the second part of the tutorial series about MVC.

In the first part, we have dig into a quick start of creating an empty ASP.NET MVC application and defined some basics. In this part, we will try to explain the mechanism of MVC and make the previous example work for the first time.

MVC is a software architecture that separates business logic from the  user interface. This is done by separating the application into three parts: the Model, the View, and the Controller.

The model is the business logic, the view is what the user see on their client device and the controller is the mechanism that serves in between them. It receives user request and perform appropriate actions.

After this brief explanation, one can easily understand why the application we created in the part one is not working properly.

ASP. NET MVC Controllers

Controllers are the mechanism for handling the user’s requests. User requests are  processed by the controllers and required actions are taken accordingly and users have responses. The most common response is an HTML output but many other types of responses can be produced.

For the newly created application in part one, we had an error message since we have NOT defined any controlers yet.

Open the MVC_DemoApp and add a new Controler as follows:

  • Right click on the Controllers folder in the solution explorer and click Add, select Controller.

5

  • Select MVC 5 Controller – Empty and press Add. Give the name as DemoController and press OK.

6

In this step do NOT delete the Controller part of the name since it is IMPORTANT for the convention.

7

In ASP.NET MVC, the name and the location of the object is important since the organization of the components are based on them.

By creating the DemoController, a class named as DemoController.cs is located under the Controllers folder. DemoController is the class name of the controller and the Demo is the name of the controller.

The code below is created automatically in the DemoController class.

namespace MVC_DemoApp.Controllers
{
public class DemoController : Controller
{
// GET: Demo
public ActionResult Index()
{
return View();
}
}
}

We have a public method called Index() in the DemoController class. Each public method in controllers is become action methods automatically. Action methods accepts user’s request and returns some response. To make a method not an action method, it must be defined some access modifiers other than public (like private etc.) or we need to add an [NonAction] attribute on top of the method if the method must be public like:

[NonAction]
public string SimpleMethod()
{
return “I am NOT an action method anymore :(“;
}

Another intresting and important thing in the Index method above is its return type. Our Index method has the return type of ActionResult and returns a View method that creates a ViewResult object which renders View to the response.

ActionResult is the abstract class and ViewResult is the child of ViewResultBase and ViewResultBase is the child of ActionResult.

ActionResult <- ViewResultBase  <- ViewResult

To keep the polymorphism in action, out Index method has the return type of ActionResult since some other result type (like Content Result) may be returned based on some criteria from the same action method.

For now, we will NOT return a View or Content. We will just return a message to the user that the request has been taken by the server. We will replce the Index method by the following MyAction method that will simply returning a string object:

public class DemoController : Controller
{
// GET: Demo
public string MyAction()
{
return “User request is handled by MyAction Method…”;
}
}

Run the application (press F5) and see the result.

4

Wowww.. This is not what we wanted to see.

What has just happened is, we make a request from our application without a controller name and an action name. Therefore our application is used the default values for the controller and the action names which are specified in the RouteConfig.cs under the App_Start folder.

RouteConfig.cs has the following line of code in it:

public class RouteConfig
{
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute(“{resource}.axd/{*pathInfo}”);

routes.MapRoute(
name: “Default”,
url: “{controller}/{action}/{id}”,
defaults: new { controller = “Home“, action = “Index“, id = UrlParameter.Optional }
);
}
}

The code marked as red are the names and the code marked as green as the values. The default controller name is Home, and the default action name is Index. When we run the application without specifying any of them these defaults are used.

In order to run our application as expected we need to specify the controller name and the action name as the “{controller}/{action}/{id}” convention.

Change the url of the browser: http://localhost:xxxxx to http://localhost:xxxxx/Demo/MyAction in order to activate the correct action while the application is still running. (If you have stopped VS IDE, you need to run the application again)

 

Up to this point, out basic MVC application now working and serving a simple text message to its users.

On the following parts, we will expand our capabilities and dig in more details…

 

References:

  1. http://www.codeproject.com/Articles/866143/Learn-MVC-Project-in-days-Day

 

Advertisements

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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 )

Google+ photo

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

Connecting to %s

%d bloggers like this: