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! š
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!
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.First, let's create a simple controller to get started.
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.
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.
To pass parameters through the URL, we can modify the action method to accept them:
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.
Let's create a simple project with a MessageController and a DisplayMessage action that accepts a message and displays it.
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!
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! šÆ