As discussed in the first chapter, all web applications receive requests from the server and produce a response, that is delivered back to the end user. A Controller does the job of receiving the request and producing the output based on the input data in ASP.NET MVC.
In this chapter, you'll be learning about the following topics:
Role of the Controller in ASP.NET MVC applications
Routing introduction and concepts
Creating your first ASP.NET 5 application
Installation of the ASP.NET Core NuGet
packages in your application
Creation of your first Controller and action
method, which returns a simple Hello World
Adding a View and making the changes that allow your Controller to use that View
Adding a Model and passing that Model data to your View
Role of the Controller in ASP.NET MVC applications
At the high level, the Controller orchestrates between the Model and the View, and sends the output back to the user. This is also the place where authentication is usually done through action filters. Action filters will be discussed in detail in the Filters section of this chapter. The following figure illustrates the high-level flow of a request (with the steps) in ASP.Net MVC and shows us how the Controller fits into the big picture:
The following is the sequence of events that will happen at high level when the user is accessing the ASP.NET Core application:
The user types the URL in the browser.
Based on the pattern of the URL, the routing engine selects the appropriate Controller.
The Controller talks to the Model to get any relevant data through its action methods. Action methods are methods within a controller
class.
The Controller then passes the data to the View to present it in a viewable format, typically as HTML elements.
The View...
The routing engine is responsible for getting the incoming request and routing that request to the appropriate Controller based on the URL pattern. We can configure the routing engine so that it can choose the appropriate controller based on the relevant information.
By convention, ASP.NET MVC follows this pattern: Controller/Action/Id.
If the user types the URL http://yourwebsite.com/Hello/Greeting/1
, the routing engine selects the Hello controller
class and Greeting action
method within the HelloController
, and passes the Id
value as 1
. You can give default values to some of the parameters and make some of the parameters optional.
The following is the sample configuration:
The template: "{controller=Hello}/{action=Greeting}/{id?}");
In the preceding configuration, we are giving three instructions to the routing engine:
Use the routing pattern controller/action/id
.
Use the default values Hello
and Greeting
for the controller
and action
respectively, if the values for controller...
Creating ASP.NET 5 application
It's time to get our hands dirty. Let us create a simple ASP.NET 5 application. Fire up Visual Studio and follow these steps:
Create a project by selecting File | New Project in Visual Studio. The first option is for creating an earlier version of the ASP.NET Web application. The second option is for creating the ASP.NET Core application using the .NET Core framework. The third option is for creating the ASP.NET Core application using the .NET framework. The difference between the second and third option is that the .NET framework supports all the functionalities of existing .NET frameworks whereas .NET Core supports only the core functionalities. The advantage of using the .NET core library is that it can be deployed on any platform.
Select the Empty template from the list of ASP.NET 5 templates. The second option is for creating the Web API application (for building the HTTP-based services) and the third option is for creating a web application containing...
Installing the ASP.NET Core NuGet package in your application
Follow these steps to install the NuGet
package of ASP.NET MVC:
Right click on the project, and select the Manage NuGet Packages option:
Select the Include Prerelease checkbox so that the NuGet Package Manager will list out all the prerelease packages. Search for MVC
and you'll get the Microsoft.AspNet.MVC package, as shown in the following result, and click on the Install button on the right-hand side:
Review the changes:
Once you click on Review Changes, the following dialog box will appear where you need to accept the license terms:
The NuGet Package Manager will download and install the ASP.NET Core and will update the project.json
file and the associated references.
Now, your project.json
file will have updated dependencies. The second line Microsoft.AspNet.Mvc
is added:
"dependencies": {
"Microsoft.AspNet.IISPlatformHandler": "1.0.0-rc1-final",
"Microsoft.AspNet.Mvc": "6.0.0-rc1-final",
"Microsoft...
Before creating the Controller, we need to remove the following app.Run
statement as this will return Hello World!
for all the incoming requests. As we want incoming requests to be handled by the controllers, we need to remove the following code from the Configure
method of the Startup
class:
app.Run(async (context) => {
await context.Response.WriteAsync("Hello World!");
});
We have installed the ASP.NET Core in our application. So, we are geared up to creating our first ASP.NET Core controller. Create a folder with the name Controllers
and add a new Controller by selecting from the context menu as shown in the following screenshot:
Once you select Add | New Item, you will be shown the following list of options. We are going to add an MVC controller class to our project:
A class will be created with the following content:
public class HomeController : Controller {
// GET: /<controller>/
public IActionResult Index() {
...
We were returning a simple string from the controller. Although that explains the concept of how the Controller
and action
method works, it is not of much practical use.
Let us create a new action
method by the name, Index2
:
public IActionResult Index2() {
return View(); // View for this 'Index2' action method
}
Now, we have created the action
method that returns a View. But we still have not added the View for the same. By convention, ASP.NET MVC would try to search for our View in the folder Views\{ControllerName}\{ActionMethod.cshtml}
. With respect to the preceding example, it will try to search for Views\Home\Index2.cshtml
. Please note that the name of the controller
folder-is Home
, not HomeController
. Only the prefix is needed as per convention. As this folder structure and file are not available, you'll get a 500 Internal Server Error when you try to access this action method through the URL http://localhost:50140/Home/Index2
.
So, let us create a folder...
Models represent your business domain classes. Now, we are going to learn about how to use the Models in our controller. Create a Models
folder and add a simple Employee
class. This is a just a plain old C# class:
public class Employee {
public int EmployeeId { get; set; }
public string Name { get; set; }
public string Designation { get; set; }
}
Create a new action
method, Employee
, in our HomeController
, and create an object of the Employee
Model with some values, and pass the Model to the View. Our idea is to use the Model employee values in the View to present them to the user:
using Chapter3.Models;
public IActionResult Employee() {
//Sample Model - Usually this comes from database
Employee emp1 = new Employee {
EmployeeId = 1,
Name = "Jon Skeet",
Designation = " Software Architect"
};
return View(emp1);
}
Now, we need to add the respective View for this action...
Passing data from Controller to View
We have just discussed how to pass the data from the Controller to the View using the Model
object. While calling the View, we are passing the model data as a parameter. But there are times when you want to pass some temporary data to the View from the Controller. This temporary data may not deserve a model
class. In such scenarios, we can use either ViewBag
or ViewData
.
ViewData
is the dictionary and ViewBag
is the dynamic representation of the same value.
Let us add the company name and company location property using ViewBag
and ViewData
as shown in the following code snippet:
public IActionResult Employee() {
//Sample Model - Usually this comes from database
Employee emp1 = new Employee {
EmployeeId = 1,
Name = "Jon Skeet",
Designation = " Software Architect"
};
ViewBag.Company = "Google Inc";
ViewData["CompanyLocation"] = "United States";
return View(emp1);...
Filters in ASP.NET MVC enable you to run code before or after a particular stage in the execution pipeline. They can be configured globally per-controller or per-action.
There are different kinds of filters, and each filter is executed at a different stage in the pipeline. For example, action filters are executed when the action
method is executed.
Let us use a simple example to see how an action filter (a type of filter) works.
I have created a simple controller, DateController
, where I am just displaying the time. In this action
method, I am using a predefined action filter by the name of ResponseCache
, that caches the response for the duration specified in seconds. In the following code snippet, we have mentioned the duration as 600 seconds. So, the response will be cached for 10 minutes.
public class DateController : Controller {
[ResponseCache(Duration = 600)]
public IActionResult Index() {
return Content(DateTime.Now.ToShortTimeString());
}
...
In this chapter, we have built our first ASP.NET 5 application from scratch and we have installed ASP.NET Core in our ASP.NET 5 application. We have learned how the controller fits into the overall ASP.NET MVC application and learned how to build your first controller with the action
methods. We also learned about how to use Model and View in our Controller. We have also discussed different ways to pass the data from the Controller to the View using ViewBag
and ViewData
. We have also learned about filters in ASP.NET MVC and how to make use of predefined filters in ASP.NET Core.