aspnet
  1. aspnet-routing

Routing - ASP.NET MVC

Routing is an essential aspect of building web applications with ASP.NET MVC. Routing maps a URL to a corresponding action method on a controller. In this page, we will discuss how to work with routing in ASP.NET MVC.

Syntax

Routing in ASP.NET MVC is defined in the RouteConfig class of the App_Start folder. Here is the syntax for defining a route:

routes.MapRoute(
    name: "RouteName",
    url: "url-pattern",
    defaults: new { controller = "ControllerName", action = "ActionName", id = UrlParameter.Optional }
);

Example

In the following example, we have created a custom route for the URL "/books/genre/{genre}".

public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

        routes.MapRoute(
            name: "BooksByGenre",
            url: "books/genre/{genre}",
            defaults: new { controller = "Books", action = "ByGenre" }
        );

        routes.MapRoute(
            name: "Default",
            url: "{controller}/{action}/{id}",
            defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
        );
    }
}

In the BooksController, we can create a corresponding action method that takes in the {genre} parameter:

public class BooksController : Controller
{
    public ActionResult ByGenre(string genre)
    {
        // retrieve books by genre and pass to view
        return View();
    }
}

Output

When a user navigates to the URL "/books/genre/horror", ASP.NET MVC would route the request to the BooksController and execute the ByGenre action method with a genre parameter value of "horror".

Explanation

Routing is the process of mapping URLs to controller action methods. In ASP.NET MVC, the RouteConfig class defines the routes for the application. Each route has a name, URL pattern, and defaults. URL parameters can be defined using tokens enclosed in braces {}.

Use

Routing is used in ASP.NET MVC to define how URLs are mapped to controller action methods. It is crucial in building user-friendly URLs and maintaining a clean URL structure.

Important Points

  • Routing is an essential aspect of building web applications with ASP.NET MVC.
  • The RouteConfig class defines the routes for the application.
  • Routing is used in ASP.NET MVC to define how URLs are mapped to controller action methods.

Summary

In this page, we discussed how to work with routing in ASP.NET MVC. We covered the syntax, example, output, explanation, use, and important points of routing. By correctly configuring routing for your application, you can achieve clean and user-friendly URLs while maintaining a clear URL structure.

Published on: