Skip to content
  • iImagine
  • Register
  • Log In

Web Development School

Learning made easy.

  • Books
    • Beginning Web Development with ASP.Net Core & Client-Side Technologies
      • TOC
      • Part 1
        • Chapter 1: Static HTML – Designing the landing page
      • Part 2
        • Chapter 2: ASP.Net Core – Let’s talk Dynamic
        • Chapter 3: Introduction to ASP.Net Core MVC
          [ASP.Net Core v9]
      • Part 4
        • Chapter 7: Using Server Side & Client Side technologies together
          [ASP.Net Core v7 & Angular 15]
  • Environment Setup
    • Installing Angular
    • Installing Visual Studio 2022
    • Installing SQL Server 2022 Express
    • Installing Postman
    • Installing Git for Windows
  • Blog
  • iImagine WebSolutions
  • Events
  • Learning Videos
  • Toggle search form

Create a Controller: Home Controller

In the last module we configured our project to run as an MVC project so that controllers could accept HTTP requests and act as Endpoints.

In this module we will create our first controller.

Table Of Contents
  1. Create the Controllers folder
  2. Create the Controller class
  3. Inherit HomeController from the Controller class
  4. Create an Action method in the Controller
  5. Controllers: controlling application flow
  6. More on Access Modifiers
  7. More on Object Oriented programming.
  8. What's Next

Create the Controllers folder

In the Solution Explorer, right click on the FredsCars project and select Add -> New Folder.

Name the new folder Controllers.

We are going to create the Home controller in the Controllers folder. Technically we could create the Home controller anywhere in the project and the application would find it. But, by convention all controllers are placed in the Controllers folder. Again, emphasizing the convention over configuration approach of MVC. Any developer familiar with MVC will look in the Controllers folder for all controllers.

Create the Controller class

The next step is to create a C# (or CSharp) class named HomeController which inherits from a class called Controller.

In Solution Explorer, right click on the Controllers folder and select Add -> Class....

In the Add New Item dialogue, name the class HomeController.cs and click the Add button.

The HomeController.cs file containing the HomeController CSharp class should now show up in the new Controllers folder we just created. And the file opens up in a new tab within Visual Studio.

The following is the code that was generated when we created a CSharp file named HomeController.cs.

FredsCars\Controllers\HomeController.cs

namespace FredsCars.Controllers
{
    public class HomeController
    {
    }
}

When you create a class in Visual Studio using the GUI (Graphical User Interface) the way we did, CSharp names the class after what you name the file excluding the [.cs] portion of the filename. The .cs extension in the filename denotes the file as a CSharp file.

So, the class definition is as follows.

public class HomeController
{
}

Think of a class as a template to create objects. An object is an instance of the template or the class. A lot of programmers mistakenly interchange these two terms. In this case, we are going to be creating object instances of the HomeController to respond to HTTP requests based off of the class template above. The two squiggly characters, {}, denote the beginning and end of a code block for the class. It is empty right now. But we will fix that shortly.

The class keyword marks HomeController as a CShap class. And the public keyword is what’s called a access modifier. Public here means that the code and methods within this class can be accessed and used by other external classes.

Notice the class definition is nested within a namespace.

namespace FredsCars.Controllers
{
    public class HomeController
    {
    }
}

Namespaces in C# and .Net are used to organize classes. We can also use namespaces to avoid duplication of class names and class name collisions.

For example, say we have one class named Type that holds the types or categories of Vehicles in our FredsCars application (Cars, Trucks, Jeeps). But then we have another class also named Type that holds the Types of customers (Organization, Individual).

The first example might live in a namespace called FredsCars.Categories. The second example might live in a namespace called FredsCars.Customers.

FredsCars.Categories.Type
FredsCars.Customers.Type

Inherit HomeController from the Controller class

The next step is to have HomeController inherit from the Controller class


Modify HomeController.cs with the code below.

FredsCars\Controllers\HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace FredsCars.Controllers
{
    public class HomeController : Controller
    {
    }
}

In the code above, we have followed the HomeController class declaration with a colon and the word Controller. The colon means inherit from and Controller is the object that HomeController will inherit.

In object oriented languages such as C#, it is common for one object to inherit functionality from another object. The parent, such as Controller in this case, is said to be the base class. And the child, such as HomeController here, is said to be the subclass.

If you hover your mouse over the Controller object, you can see Microsoft’s definition for it.

A base class for an MVC Controller with view support.

In order to access the Controller base object to inherit from, we have to import it’s namespace with a using statement.

using Microsoft.AspNetCore.Mvc;

Without this using statement, ASP.Net Core will not know where to find the Controller base class. With it, it knows to look in the Microsoft.AspNetCore.Mvc namespace.

Create an Action method in the Controller

Modify your HomeController.cs file with the code below.

FredsCars\Controllers\HomeController.cs

using Microsoft.AspNetCore.Mvc;

namespace FredsCars.Controllers
{
    public class HomeController : Controller
    {
        public ViewResult Index()
        {
            return View();
        }
    }
}

In the code above we created a method in the HomeController class called Index that returns a ViewResult object.

Methods in C# classes are functions that contain the functionality of the object. And methods in C# Controller classes that can return a response to an incoming URL request are called Actions or Action Methods.

Let’s inspect the new bit of code.

public ViewResult Index()
{
    return View();
}

The name of the action is called Index. It returns an object of type ViewResult and again is marked with the public access modifier meaning external objects can see, access, and use this method (as long as the class itself is also marked as public).

This action method only has one line of code.

return View();

Most functions or methods return a value or an object. If it doesn’t we mark the return type as void rather then an object type like ViewResult. If the Index action method did not return a value it might look something like this.

public void Index()
{
    // doing my thing.
    //  don't return anything.
}

Again look at the one line of code in the Index action method.

return View();

The return keyword exits a function or method and returns a value or an object. In this case it returns the results of calling the View() method.

The View() method creates a ViewResult object and returns it to the incoming HTTP request.

Controllers: controlling application flow

Part of the definition I gave for Controllers in the MVC Architecture section of Chapter 3-Module 1: Introduction to ASP.Net Core MVC, is the following.

Controls application flow.

For the HomeController class, this means that any of the following URL requests will be fullfilled by the HomeController’s Index method.

https://localhost:40443/
https://localhost:40443/Home
https://localhost:40443/Home/Index

This is because of the default route we set up back in program.cs.

app.MapDefaultControllerRoute();

And recall the default route that MapDefaultControllerRoute sets up:

{controller=Home}/{action=Index}/{id?}

So if the incoming URL is: https://localhost:40443/Home/Index, then we are explicitly saying in the first URL segment after the base URL, go to the Home Controller. And we are saying in the second URL segment, use the Index action.

And if the incoming URL is: https://localhost:40443/Home, then we are explicitly saying in the first and only URL segment after the base URL, go to the Home Controller. And we are implicitly saying use the Index action because Index is the default action in our default route.

And if the incoming URL is: https://localhost:40443, then we are implicitly saying go to the Home Controller because Home is the default Controller in our default route. And we are implicitly saying use the Index action because Index is the default action in our default route.


Notice when the controller in the URL is Home, explicitly or implicitly, ASP.Net Core MVC looks for a Controller class called HomeController. We do not have to specify Controller in the URL.

More on Access Modifiers

When we created the HomeController class, I talked about the public access modifier for for the class and the Index Action Method.

There are actually four main access modifiers in C#.

publicThe code is accessible for all classes
privateThe code is only accessible within the same class
protectedThe code is accessible within the same class, or in a class that is inherited from that class.
internalThe code is only accessible within its own assembly, but not from another assembly.

There are also two less frequently used access modifiers called protected internal and private protected.

In this book we will mostly be seeing public and private. But you can read more about access modifiers at w3Schools.

More on Object Oriented programming.

I’ve kind of put the cart before the horse here getting into object oriented programming in C# before going over sequential statements, ‘if then else’ and switch statements, and looping. These programming structures are usually covered when learning a programming language before getting into the OOP (Object Oriented Programming) aspects of the language. In this case it was necessary to dive in to OOP early while creating our first controller.

However these programming structures are very similar in most programming languages and we did look at them for JavaScript back in Chapter 1 in the Programming Structures section of module 7.

This is not a book about C# but rather a book about ASP.Net Core. But since this book is supposed to be for anyone even if an absolute beginner I am trying to fill in enough detail about C# as we go to follow along. There should be less detail in the next chapter about Razor Pages. But for now bear with me.

If you want to read more about C# you can read Microsoft Official Documentation and tutorials or the tutorials at w3schools.

What’s Next

In this module we created our first controller and action method.

In the next module we will create a View for the Index Action in the HomeController.

< Prev
Next >

Leave a ReplyCancel reply

Chapter 1: Static HTML – Designing the landing page.

  • Static HTML – Designing the landing page.
  • Let’s get started!
  • Mock your site with HTML
  • Make CSS easy with Bootstrap
  • Mock your content
  • Introducing JavaScript
  • JavaScript Code Improvements
  • Results Data
  • Images and the HTML Image Element.
  • Revisiting Reusability for CSS and JavaScript
  • Reuse for HTML: PART 1
  • Reuse for HTML: PART 2
  • Details Page – Using a Bootstrap Component
  • Creating Links
  • Chapter One Conclusion

Chapter 2: ASP.Net Core – Let’s talk Dynamic

  • Introduction to ASP.Net Core
  • What is .Net?
  • What is ASP.Net
  • Introduction to Entity Framework Core

Chapter 3: ASP.Net MVC Core – Models, Views, and Controllers [ASP.Net Core v9]

  • Introduction to ASP.Net Core MVC
  • Create the project: ASP.Net Core MVC
  • Explore the ASP.Net Core Empty Web Project Template
  • Configure the Application for MVC
  • Create a Controller: Home Controller
  • Create a View: Index View for the Home Controller
  • Install Bootstrap using Libman
  • Create the Layout template
  • Create the Model
  • Install EF Core & Create the Database
  • Seed the Database: Loading test data
  • DI (Dependency Injection): Display a List of Vehicles
  • Repository Pattern: The Vehicles Repo
  • Unit Test 1: Home Controller Can Use Vehicle Repository
  • Unit Test 2: Vehicle Repository Can Return List
  • Add the ImagePath Migration and Thumbnail images to results
  • Pagination: Create a Custom Tag Helper
  • Sorting
  • Category Filter
  • Partial View: Break out the vehicle results
  • View Component: Create dynamic category buttons
  • Create the Details page
  • Create the Create Page

Chapter 7: Using Server Side & Client Side technologies together. [ASP.Net Core v7 & Angular v15]

  • Intro to Full Stack Development
  • Fred’s Cars – Full Stack Development
  • Prepare the environment
  • Create the Visual Studio Solution
  • Add the ASP.Net Core Web API project
  • Add the Angular Project
  • Wire it up!
  • WeatherForecast: Understanding the basics
  • Vehicles API Controller: Mock Data
  • Vehicles Angular Component: Consuming Data
  • Routing and Navigation
  • Using a Component Library: Angular Material
  • Our first Angular Material Component: MatToolbar
  • Configuring for Saas: CSS with superpowers
  • Create the Header & Footer components
  • Displaying Results with MatTable
  • Loading: Using a Progress Spinner
  • MatTable: Client-Side Paging and Sorting
  • MatSidenav: Create a Search Sidebar
  • MatCheckbox: Category Search UI
  • Adding an image to the welcome page
  • Create the database with Entity Framework Core migrations
  • MatPaginator & PageEvent: Custom Server-Side Paging
  • Unit Testing: Custom Server-Side Paging
  • Repository Pattern: VehicleRepository
  • Unit Test: Paging in the Vehicles controller
  • Server-Side Sorting
  • Unit Tests: Sorting
  • Filter (Quick Search)
  • Unit Tests: Filter feature
  • Advanced Search: Categories
  • Unit Tests: Search by category
  • Progress Spinner: Final Fix

TOC

  • What were WebForms?
  • Enter MVC
    • Understanding MVC
    • Advantages of MVC
  • ASP.Net Core MVC – A total rewrite
  • ASP.Net Core 2 MVC – Here come Razor Pages
    • Understanding Razor Pages
  • ASP.Net Core 3 – Dropping the MVC reference
    • Understanding Blazor
  • Dropping the MVC reference
  • Hello .Net 5!
  • What’s Next? – Here comes .Net 6.

Recent Posts

  • Angular Commands Cheat Sheet
  • Installing Git for Windows
  • Installing Postman
  • Installing SQL Server 2022 Express
  • Installing Visual Studio 2022

Recent Comments

No comments to show.

Archives

  • November 2023
  • October 2023
  • June 2023
  • October 2021

Categories

  • Angular
  • ASP.Net
  • Environment Setup
  • See All
  • SQL Server
  • Visual Studio
  • Web API & Rest Services

WordPress Theme Editor

Copyright © 2025 Web Development School.

Powered by PressBook Blog WordPress theme