TheBoubou
TheBoubou

Reputation: 19933

Define route in ASP.NET MVC

I defined the a new route (see below). When I launch the application, I'd like by default:

When I use this configuration, I start on Home/Index it's ok but /Customer/Detail/MyCode give a null value all the time.

If I inverse the routes.MapRoute, I have :

Any idea ?

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

routes.MapRoute(
    "CustomerDetail",
    "{controller}/{action}/{code}",
    new { controller = "Customer", action = "Detail", code = UrlParameter.Optional }
);

Upvotes: 0

Views: 470

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1039438

A single route will be enough:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{code}", // URL with parameters
    new { controller = "Home", action = "Index", code = UrlParameter.Optional } // Parameter defaults
);

When you request Home/Index this will invoke the Index action on HomeController and pass null as the code parameter and when you request Customer/Detail/MyCode the Detail action will be invoked on CustomerController and passed code=MyCode.

The reason you were getting null is that both your routes are equivalent, meaning that they are of the form Controller/Action/SomeCode which means that for both urls the first route is matched, but the parameter is called id instead of code so you are getting code=null. Another possibility is to simply leave the default route as is:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

and then rename the parameter to the Detail action to id:

public ActionResut Detail(string id)
{
    // if you request Customer/Detail/MyCode the id parameter will equal MyCode
}

Upvotes: 3

Related Questions