Routing consists of creating an address for a webpage and open such a webpage when a visitor clicks the link. The actual webpage is either generated from scratch or is incomplete because it depends on the link the user would click.

Practical Learning: Introducing Routing

Start Microsoft Visual Studio

On the main menu, click File -> New Project...

In the New Project dialog box, make sure ASP.NET Web Application (.NET Framework) is selected in the middle list.
Change the Name of the project to TrafficTicketSystem1

using System.Web.Mvc;
namespace TrafficTicketSystem1.Controllers
{
public class ViolationsController : Controller
{
// GET: Violations
public ActionResult Index()
{
Models.TrafficTicketsSystem tts = new Models.TrafficTicketsSystem();
/* Get the list of violations for our local database.
* Store that list of violations in a ViewBag so we can use it in a view. */
ViewBag.Violations = tts.violations;
return View();
}
}
}

In the document, right-click anywhere inside the Index() method and click Add View...

To support routing, the .NET Framework provides a class named RouteCollection. This class is derived from the Collection<T> class of the System.Collections.ObjectModel namespace:

public class RouteCollection : Collection<RouteBase>

The RouteCollection class is defined in a namespace named System.Web.Rounting. As its name indicates, RouteCollection is a collection class used to create and manage a list of items. The class is equipped with all types of properties and methods to add and manage its values.

Besides its members, the RouteCollection class is expanded with many extended methods. For example, to let you specify a routing scheme, the RouteCollection class is equipped with an overloaded method named MapRoute. One of its versions uses the following syntax:

A Web Route is specified using a formula that follows some rules. This is the role of the url argument of the RouteCollection.MapRoute() method. The argument is a string that contains a scheme, called a URL pattern, that resembles the path or address of a webpage. The formula it follows is:

{controller}/{action}/{id}

As you can see, this string uses a few placeholders. The most-left placeholder specifies that a path starts with a controller. Here is an example:

The url argument indicates that the controller is followed by the name of an action method. This means that you must create such a controller. By tradtion, that method is named Details. Here is an example:

The address of a route ends with a value that can be used to select a webpage or a value to display. This can be a value that uniquely idenfies a page or a record. In most cases (or to make things easier), this value is named id and is of type integer. To get ready to use it, pass it as argument to the action method you are creating. You must anticipate that, at times, the value of this identifier will not be provided, for any reason. Therefore, the method must be able to handle null values. For this reason, the argument must be passed as a possible null. If you are passing it as a primitive type such as an integer, add a question mark to it. Here is an example:

The last argument, defaults, is an anonymous object. Therefore, define it using the new operator and curcly brackets. In the brackets, use each of the factors from the url argument and assign the appropriate value. The value you provide is not case-sensitive. This means that in this case, academics is the same as Academics and is the same as ACADEMICS. When you have specified this name, when the webserver is asked to display the webpage, the compiler will look for a controller that has that name in the current Web project. If there is not a controller with that name, the browser will display an error as "The resource cannot be found". Therefore, make sure you provide an existing controller name.

After assigning the name of a controller, specify the name of the desired action to access. If the controller exists, the compiler will look for the indicated action method in the controller class. If the action method doesn't exist in the controller, the browser will display an error as "The resource cannot be found". Therefore, make sure you assign an existing action method to action.

If you are not planning to use an identifier in the address, assign UrlParameter.Optional to Id. If you are planning to use an identifier in the address, assign it to Id. When the webserver is asked to display the webpage, it it finds an identifier with the indicated value, it would display it.

To make your code easy to read, you can apply each argument to the name of the corresponding argument used in the syntax of the method. Here is an example:

Another method of the RouteCollection class indicates a URL scheme that should be ignored. This method is named IgnoreRoute. Its syntax is:

public void IgnoreRoute(string url);

This method takes one argument as a string that contains the URL pattern.

In the action method that handles the route, write code to select a record. Normally, to select a record, you would call a method of the class that handles the collection of records. That collection should (must) provides the means to use the value passed as argument to select a record that be uniquely identified by that value. Once you have selected the record, you can display it in a view.

To execute the project, on the main menu, click Debug -> Start Without Debugging

In the address bar, click on the right side of the address, type /Details/3

Press Enter

In the address bar, change 3 to 9

Press Enter

Close the browser and return to your programming environment

A Link for a Route

To lead the users to a view that can show a record, you can create a link from a webpage that displays a list of records. To start, when the user accesses the records, each record displays on its own row. Remember that each record should (must) have a value that uniquely identifies it. you can create a link so that, when the user positions the mouse on it, the unique value would be selected. You can then create a link on that value. To let you do this, the HtmlHelper class is extended with various versions of the ActionLink() method. One of the versions uses the following syntax:

As mentioned in previous lessons, the first argument, linkText, is the text of the link. The second argument, actionName, is the name of the action method from a controller class. The new argument, routeValues, is of type object and represents the route. The argument is passed as an anonymous object: new {}. In the curly brackets, assign the unique record value to the argument passed to the action method.

Practical Learning: Creating a Link for a Route

Access the Index.cshtml file of the ViolationsController class and change the document as follows:

To execute the project, on the main menu, click Debug -> Start Without Debugging

In the address bar, click on the right side of the address, type /Details/1 and press Enter

In the address bar, change 1 to 4 and press Enter

Click the Traffic Violations link

In the webpage, click the Citation link for the 2nd record

Click the Traffic Violations link

In the webpage, click the Citation link for the 6th record

Close the browser and return to your programming environment

At Application Start-Up

To let you indicate how the routing must be done in your ASP.NET MVC project, when you create a project in Microsoft Visual Studio, the studio creates a folder named App_Start in the project. In that folder, it creates a C# file named RouteConfig.cs. In that file, it creates a class named RouteConfig. In that class, it creates a static method named RegisterRoutes. The compiler will refer to that class for routing purposes.

Practical Learning: Routing in MVC

In the Solution Explorer, expand App_Start if necessary and double-click RouteConfig.cs to open it

To execute the project, on the main menu, click Debug -> Start Without Debugging:

Close the browser and return to your programming environment

The Entry Page of a Web Site

When you decide to create a website, the most important object is a file named the entry webpage. This is the webpage that displays when a visitor types a domain name (such as yahoo.com, microsoft.com, or csharpkey.com, etc) in the address bar of a browser and presses Enter. Behind-the-scenes, that is, in the webserver, this file is usually named index, Index, default, or Default, and has the extension .htm, .html, or something like that. This is neither a rule nor a law, only a routine. When creating your website, you can decide what webpage must display when.

Practical Learning: Introducing Routing

On the main menu of Microsoft Visual Studio, click File -> New -> Project...

In the New Project dialog box, click ASP.NET Web Application (.NET Framework).
Change the project Name to DepartmentStore09

Press Enter

In the New ASP.NET Web Application dialog box, click the MVC icon and click OK. Notice the DepartmentStore09 tab

To create a new controller, in the Solution Explorer, right-click Controllers -> Add -> New Scaffolded Item...

To execute the project, on the main menu, click Debug -> Start Without Debugging:

Close the browser and return to your programming environment

Options on Creating Routes

Ignoring the Indentifier

When a webserver is asked to display a webpage, it switches to the routing configuration and checks the Id factor. If the Id is specified but there is no such identifier, it would be ignored. If you are not planning to use the Id factor, you can assign an empty string to Id. Here is an example:

As mentioned previously, the class used to create routes, RouteCollection, is a collection class. This means that you can create and manage as different routes as you want. Each route is created by calling the RouteCollection.Add() method that we saw already. Here are examples:

After creating the routes, if a visitor accesses your website using the domain name (such as blahblahblah.com), the webserver will refer to the RouteConfig.cs file and enter the RouteConfig.RegisterRoutes() method. As is always the case, the compiler would read the document from top to bottom. As a result, the first route would apply and may show its indicated webpage even if that's not the regular entry-poinit. Otherwise, the webserver would follow or access the views (the webpages) by the order of the routes creations.

View Redirection Using a Route

When an action has been performed, you can redirect the user or visitor to a view of your choice by specifying a route to take. To support this, the Controller class is equipped with an overloaded method named RedirectToRoute. One of the syntaxes used by this method is: