DEV Community

Carren Chepkorir
Carren Chepkorir

Posted on

Routing in MVC

Understanding Routing: Beginners Guide

This article explains routing in MVC. How a route in MVC is executed by the routing engine and how to define a route for a URL
Table of contents;
1.Overview of .Net mvc
2.Properties of Route
3.Default Routes
4.Code Snippets
5.Conclusion

Overview of .Net MVC
ASP.NET MVC is a web development framework developed by Microsoft. It is a part of the larger .NET framework and provides a pattern-based approach to building web applications. The MVC pattern separates the application into three main components: the Model, View, and Controller. Let's take a closer look at each component:

Model:
The Model represents the data and business logic of the application. It defines behavior of the data. This component typically includes classes that interact with the database, perform data validation, and contain business rules and calculations.

View:
The View is responsible for the presentation layer of the application. It manages display of data. Views are usually created using HTML, CSS, and server-side markup (typically Razor syntax in ASP.NET MVC). Views are lightweight and focus on rendering the data provided by the controller.

Controller:
The Controller acts as an intermediary between the Model and the View. It handles user interactions, processes requests, and updates the Model accordingly. Controllers receive input from the user via the View, perform necessary actions, and then pass the updated Model to the appropriate View for rendering.
The flow of data and control in ASP.NET MVC typically follows these steps:

1.The user interacts with the application by sending a request to the server.
2.The routing mechanism in ASP.NET MVC maps the incoming request to a specific controller action.

  1. The controller action processes the request, interacts with the Model if required, and prepares the data to be displayed. 4.The controller selects the appropriate View and passes the prepared data to it. 5.The View receives the data and renders the HTML markup that will be sent back to the user's browser. 6.The rendered HTML is then sent back to the user's browser as a response. **

Properties of Routes in MVC

**
Here are the key properties of routes in MVC:

1.URL pattern:
A route specifies a URL pattern of the structure of the incoming request's URL. The pattern can contain placeholders for dynamic segments, such as {controller}, {action}, and additional route parameters. For example, the pattern /products/{id} can match URLs like /products/1, /products/2, and so on.

2.Controller and action:
Routes determine which controller and action should be invoked to handle a request. The {controller} and {action} placeholders in the URL pattern are replaced with the actual names of the controller and action. For instance, a URL like /home/index would be handled by the Index action in the HomeController.

3.Route parameters:
Routes can include additional parameters defined within the URL pattern. These parameters capture specific values from the URL and pass them to the controller action. For example, in the route pattern /products/{id}, the id parameter would be extracted from the URL and made available to the corresponding action method.

4.Defaults:
Defaults allow you to specify fallback values or make certain parameters optional. For instance, a route with the pattern /products/{id} might have a default value for id set to 0, ensuring that the id parameter is always present.Let's talk more about Default routes in next part.

Constraints:
Route constraints allow you to specify additional rules for parameter values. Constraints define validation conditions that must be met for a route to match. For example, you can define a constraint to ensure that the id parameter in a route only matches numeric values.

Route ordering:
In MVC frameworks, routes are evaluated in the order they are defined. The first matching route is used to handle the request. Therefore, the order in which routes are registered can be crucial. More specific routes or routes with constraints should be defined before more generic ones to ensure the correct route is selected.
**

Default routes

**
Let's look at the default routes

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

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

Enter fullscreen mode Exit fullscreen mode

name: The name of the route. It is optional and can be used to reference the route elsewhere in the application.
url: The URL pattern that the route matches. By convention, it consists of three segments: {controller}/{action}/{id}. This pattern indicates that the route expects a controller name, an action name, and an optional id parameter in the URL.
defaults: In this case, the default controller is "Home", the default action is "Index", and the id parameter is optional. If no specific values are provided in the URL, these defaults will be used.

**

Conclusion

**
It's important to note that you can modify the default route configuration or add additional routes to handle different URL patterns according to your application's requirements. However, it's generally recommended to follow the conventions and keep the default route as a fallback option for unmatched URLs.

Top comments (0)