ASP .NET Tutorial: Conventional Routing šŸŽÆ

beginner
22 min

ASP .NET Tutorial: Conventional Routing šŸŽÆ

Welcome to the ASP .NET routing lesson! In this tutorial, we'll learn about conventional routing, a powerful feature that helps us navigate through our application. Let's get started! šŸ“

What is Conventional Routing?

In ASP .NET, conventional routing is a way to map URLs to specific controller actions without having to define explicit route templates. It's called "conventional" because it follows a set of conventions that make it easy to work with.

šŸ’” Pro Tip: Conventional routing simplifies our lives by reducing the amount of code we need to write!

Understanding the Route Structure

To better understand conventional routing, let's look at its structure:

/controller/action/id
  • controller: The name of the controller handling the request.
  • action: The action method within the controller that will be executed.
  • id: An optional parameter that can be used to pass data to the action method.

Creating a Controller

First, let's create a simple controller to get started.

csharp
using Microsoft.AspNetCore.Mvc; namespace MyApp.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } } }

In the code above, we created a HomeController with an Index action that returns a view.

Setting Up the Route

Now, let's see how ASP .NET automatically sets up the route for our controller:

/ --> HomeController.Index

By default, ASP .NET maps the root URL ("/") to the Index action of the default controller (in this case, HomeController). This is because ASP .NET follows the Controller and Action naming conventions.

Adding Parameters to the URL

To pass parameters through the URL, we can modify the action method to accept them:

csharp
public IActionResult DisplayMessage(string message) { ViewData["Message"] = message; return View(); }

Now, let's create a route that accepts a parameter:

/message/id --> HomeController.DisplayMessage(id)

With the above routing, we can access the DisplayMessage action with a URL like /message/Hello World.

Practical Example šŸ“

Let's create a simple project with a MessageController and a DisplayMessage action that accepts a message and displays it.

csharp
using Microsoft.AspNetCore.Mvc; namespace MyApp.Controllers { public class MessageController : Controller { public IActionResult DisplayMessage(string message) { ViewData["Message"] = message; return View(); } } }

Now, navigate to /message/Hello World to see the message displayed!

Quiz šŸ’”

Quick Quiz
Question 1 of 1

How can we access the `DisplayMessage` action in ASP .NET with a URL like `/message/Hello World`?

That's it for today! In the next lesson, we'll explore more advanced routing techniques in ASP .NET. Stay tuned! šŸŽÆ