Skip to main content

ASP.NET MVC Routing


ASP.NET MVC Routing


ASP.NET MVC routing is a pattern matching system that is responsible for mapping incoming browser requests to specified MVC controller actions. When the ASP.NET MVC application launches then the application registers one or more patterns with the framework's route table to tell the routing engine what to do with any requests that matches those patterns. When the routing engine receives a request at runtime, it matches that request's URL against the URL patterns registered with it and gives the response according to a pattern match.

Routing pattern is as follows


A URL is requested from a browser, the URL is parsed (that is, break into controller and action), the parsed URL is compared to registered route pattern in the framework’s route table, if a route is found, its process and send response to the browser with the required response, otherwise, the HTTP 404 error is send to the browser.

Route Properties


ASP.NET MVC routes are responsible for determining which controller method to execute for a given URL. A URL consists of the following properties:
  • Route Name: A route is a URL pattern that is mapped to a handler. A handler can be a controller in the MVC application that processes the request. A route name may be used as a specific reference to a given route.
     
  • URL Pattern: A URL pattern can contain literal values and variable placeholders (also known as URL parameters). The literals and placeholders are located in segments of the URL that are delimited by the slash (/) character.

    When a request is made, the URL is parsed into segments and placeholders, and the variable values are provided to the request handler. This process is similar to the way the data in query strings is parsed and passed to the request handler. In both cases variable information is included in the URL and passed to the handler in the form of key-value pairs. For query strings both the keys and the values are in the URL. For routes, the keys are the placeholder names defined in the URL pattern, and only the values are in the URL.
     
  • Defaults: When you define a route, you can assign a default value for a parameter. The defaults is an object that contains default route values.
     
  • Constraints: A set of constraints to apply against the URL pattern to more narrowly define the URL that it matches.
     

The Default Route


The default ASP.NET MVC project templates add a generic route that uses the following URL convention to break the URL for a given request into three named segments.

url: "{controller}/{action}/{id}"

This route pattern is registered via call to the MapRoute() extension method of RouteCollection. As shown in the below figure.



When an MVC application first starts, the Application_Start() method is called. This method, in turn, calls the RegisterRoutes() method. The RegisterRoutes() method creates the route table.

The default route table contains a single route (named Default). The Default route maps the first segment of a URL to a controller name, the second segment of a URL to a controller action, and the third segment to a parameter named id.

Imagine that you enter the following URL into your web browser's address bar:
/Guests/Index/3

The Default route maps this URL to the following parameters:
·         controller = Home
·         action = Index
·         id = 3

When you request the URL /Home/Index/3, the following code is executed:
GuestsController.Index(3)

The Default route includes defaults for all three parameters. If you don't supply a controller, then the controller parameter defaults to the value Guests. If you don't supply an action, the action parameter defaults to the value Index. Finally, if you don't supply an id, the id parameter defaults to an empty string.

Let's look at a few examples of how the Default route maps URLs to controller actions. Imagine that you enter the following URL into your browser address bar:
/Guests

Because of the Default route parameter defaults, entering this URL will cause the Index() method of the GuestsController class as in Listing below to be called.

// GET: Guests
        public ActionResult Index()
        {
            return View(db.Guests.ToList());
        }

ASP.NET MVC Routing with an Example


When the application starts up, ASP.NET MVC discovers all of the application's controllers by searching through the available assemblies for a class that implements the System.Web.Mvc.IController interface or derived from a class that implements this interface and whose class names end with the suffix Controller. When the routing framework uses this list to determine which controller it has access to, it removes the Controller suffix from the entire controller class names.

In our previous article, WebApp Tutorial with ASP.NET MVC using Model First Approach, we implemented Create, Read, Update and Delete operations on a Guest entity. So we will use this example to understand URL routing. Our default route is the same as shown below for CRUD applications also.

URL
Controller
Action
Id
GuestsController
Index

http://localhost:44302/Guests/
GuestsController
Index

http://localhost:44302/Guests/Create
GuestsController
Create

http://localhost:44302/Guests/Edit/1
GuestsController
Edit 
1
  
The last request's URL (http://localhost:44302/Guests/Edit/1) in above table is a perfect match to the registered default URL pattern because it satisfies every segment of the route pattern, but when we don't provide a complete request's URL then the routing engine automatically calls the controller and action method as per the default route pattern.

Multiple Routes


You can also configure a custom route using MapRoute extension method. You need to provide at least two parameters in MapRoute, route name and url pattern. The Defaults parameter is optional.

You can register multiple custom routes with different names. Consider the following example where we register "Guests" route.
public class RouteConfig
{
    public static void RegisterRoutes(RouteCollection routes)
    {
        routes.IgnoreRoute("{resource}.axd/{*pathInfo}");

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

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

Register Routes


Now, after configuring all the routes in RouteConfig class, you need to register it in the Application_Start() event in the Global.asax. So that it includes all your routes into RouteTable.

Route Registration


using System.Web.Routing;

namespace GuestInfoTutorial
{
    public class MvcApplication : System.Web.HttpApplication
    {
        protected void Application_Start()
        {
            RouteConfig.RegisterRoutes(RouteTable.Routes);
        }
    }
}


Summary


We have examined the default route table that we get with a new ASP.NET MVC application. We also learned how the default route maps URLs to controller actions

We should be noted that controller and action values in the route are not case-sensitive. URL route patterns are relative to the application root, so they don't need to start with a forward slash (/) or virtual path designator (~/).

This article is referenced from the articles of Stephen Walther , SandeepSingh and TutorialTeacher

Comments

Popular posts from this blog

Classes in C# Explained

C# Class Explained A class is nothing but an encapsulation of properties and methods that are used to represent a real-time entity, as explained by Guru99 . For instance, if you want to work with Guest’s data as in our previous DataDriven Web application . The properties of the Guest would be the Id, GuestName, Address, Phone number etc of the Guest. The methods would include the entry and modification of Guest data. All of these operations can be represented as a class in C# as shown below. using System; namespace CsharpnaijaClassTutorial {     public class Guest     {         public int Id { get ; set ; }         public string GuestName { get ; set ; }         public string Address { get ; set ; }         public string WhomToSee { get ; set ; }     ...

ASP.NET MVC Views

Views in ASP.NET MVC Application explained Find a related article By  Steve Smith  and  Luke Latham from Microsoft Corporation here In the Model-View-Controller (MVC) pattern, the  view  handles the application's data presentation and user interaction. A view is an HTML template with embedded  Razor markup . Razor markup is code that interacts with HTML markup to produce a webpage that's sent to the client. In ASP.NET MVC, views are  .cshtml  files that use the  C# programming language  in Razor markup. Usually, view files are grouped into folders named for each of the application's  controllers . The folders are stored in a  Views  folder at the root of the application as shown: The  Home  controller is represented by a  Home  folder inside the  Views  folder.  The  Home  folder contains the views for the  About ,  Contact , and  Index...