Define route in ASP.NET MVC
I defined the a new route (see below). When I launch the application, I'd like by default:
- Go Home/Index
- If I go to /Customer/Detail/MyCode get "MyCode"
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 :
- By default I go to /Customer/Detail and I get mycode value all the time (no nu开发者_开发百科ll anymoe)
- I don't start on /Home/Index
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 }
);
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
}
精彩评论