Jesse
Jesse

Reputation: 469

ASP.NET MVC4 Routing - Multiple routes to the same location

I am in the process of setting up a Single Page Application (SPA) and would like to setup, currently two routes. For instance:

In the admin area, they setup the <client> and <clients project name>, therefore I know I need to setup this configuration in MVC4 Routes, but it is unclear to me how I would approach this.

Another caveat would be, if the <clients project name> was not entered into the URL, it would present a search page for that client.

Upvotes: 2

Views: 8454

Answers (1)

Colin Bacon
Colin Bacon

Reputation: 15609

One of the great things about routing in MVC is the ability to route anything to anywhere, regardless of whether the url matches the naming of controllers and action methods. The RouteConfig allows us to register specific routes to cater for this. Let me show you how you can achieve this.

Route 1:

This is handled by the default route in the route config.

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

Hitting http://localhost will take you to the Home controller and the Index action method.

Route 2:

We can set up one route that will cater for http://localhost/<client> and http://localhost/<client>/<clients project name>

routes.MapRoute(
    "Client", 
    "{client}/{title}", 
    new { controller = "Home", 
          action = "Client", 
          title = UrlParameter.Optional });

Hitting either http://localhost/bacon or http://localhost/bacon/smokey will take you to the Home controller and the Client action method. Notice the title is an optional parameter this is how we can get both urls to work with the same route.

For this to work on the controller end our action method Client would need to look like this.

public ActionResult Client(string client, string title = null)
{
    if(title != null)
    {
       // Do something here.
    }
}

Upvotes: 6

Related Questions