Reader small image

You're reading from  Learning ASP.NET Core MVC Programming

Product typeBook
Published inNov 2016
Reading LevelIntermediate
PublisherPackt
ISBN-139781786463838
Edition1st Edition
Languages
Right arrow
Authors (2):
Mugilan T. S. Ragupathi
Mugilan T. S. Ragupathi
author image
Mugilan T. S. Ragupathi

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsof technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, www.dotnetodyssey.com, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 (http://www.dotnetodyssey.com/asp-net-mvc-5-free-course/) was well received and is referred to as a concrete reference for beginners. He can be seen on subreddit / Stack Overflow in the C# section. He has written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C# (http://www.dotnetodyssey.com/freeebooks/). His books have received good responses. He is also an active contributor to the ASP.NET community on Quora (https://www.quora.com/profile/Mugil-Ragu). He likes to help readers with queries regarding ASP.NET.
Read more about Mugilan T. S. Ragupathi

Anuraj Parameswaran
Anuraj Parameswaran
author image
Anuraj Parameswaran

Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
Read more about Anuraj Parameswaran

View More author details
Right arrow

Chapter 3. Controllers

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:

  1. The user types the URL in the browser.

  2. Based on the pattern of the URL, the routing engine selects the appropriate Controller.

  3. The Controller talks to the Model to get any relevant data through its action methods. Action methods are methods within a controller class.

  4. The Controller then passes the data to the View to present it in a viewable format, typically as HTML elements.

  5. The View...

Introduction to routing


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:

  1. 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.

  2. 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:

  1. Right click on the project, and select the Manage NuGet Packages option:

  2. 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:

  3. Review the changes:

  4. 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...

Our first Controller


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() { 
...

Adding Views


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...

Adding Models


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


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()); 
  } 
...

Summary


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.

lock icon
The rest of the chapter is locked
You have been reading a chapter from
Learning ASP.NET Core MVC Programming
Published in: Nov 2016Publisher: PacktISBN-13: 9781786463838
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
undefined
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $15.99/month. Cancel anytime

Authors (2)

author image
Mugilan T. S. Ragupathi

Mugilan T. S. Ragupathi has been working on building web-based applications using Microsof technology for more than a decade. He is active in the ASP.NET community and is running a successful blog, www.dotnetodyssey.com, to help his fellow .NET developers. His free beginners' course for ASP.NET MVC 5 (http://www.dotnetodyssey.com/asp-net-mvc-5-free-course/) was well received and is referred to as a concrete reference for beginners. He can be seen on subreddit / Stack Overflow in the C# section. He has written two free micro e-books, The 7 Most Popular Recipes of jQuery with ASP.NET Web Forms and Value & Reference types in C# (http://www.dotnetodyssey.com/freeebooks/). His books have received good responses. He is also an active contributor to the ASP.NET community on Quora (https://www.quora.com/profile/Mugil-Ragu). He likes to help readers with queries regarding ASP.NET.
Read more about Mugilan T. S. Ragupathi

author image
Anuraj Parameswaran

Anuraj Parameswaran is a seasoned IT expert with over 19 years of experience, starting in 2004, with a strong focus on Azure and .NET technologies. Currently serving as the Chief Technology Officer (CTO) of Socxo Solutions Pvt. Ltd., he has received seven prestigious Microsoft MVP awards. Anuraj actively participates in mentoring programs, delivers speeches at various events, and contributes extensively to both Microsoft and Azure communities. His commitment to sharing knowledge and embracing lifelong learning is exemplified by his involvement as a technical reviewer for Packt books.
Read more about Anuraj Parameswaran