Reputation: 1559
I have this RegisterRoute function
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("JsActionRoute", JsAction.JsActionRouteHandlerInstance.JsActionRoute);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
Where the JsActionRoute is a route like this.
public static readonly Route JsActionRoute = new Route("JsAction",
new JsAction.JsActionHandler());
I want that all links to JsAction/ should be handled by my coustom route.
Now when simply calling @Html.ActionLink
, Mvc3 creates a link that is related to JsAction, and I can't understand why.
@Html.ActionLink("About","About") -> JsAction?Action=About&Controller=Index
Upvotes: 2
Views: 368
Reputation: 1039328
Routes are evaluated in the same order as they are registered. You could use the RouteLink
to explicitly specify a route name:
@Html.RouteLink("About", "Default", new { action = "About" })
If you inverse the order of definitions then links will generate correctly but your custom route will not be hit when requesting the JsAction/
url since there is nothing to disambiguate this url from the default route.
You will have to rethink your routes structure so that there are no such conflicts. You could use constraints. Remember that the default route is very eager and if you don't constrain it, it will often take precedence.
One possibility is to define a controller and action for your custom route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.Add("JsActionRoute", JsAction.JsActionRouteHandlerInstance.JsActionRoute);
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
);
}
and then constrain the custom route by specifying a controller and action to be executed:
public static readonly Route JsActionRoute = new Route(
"JsAction",
new RouteValueDictionary(new { action = "JsAction", controller = "Foo" })
new JsAction.JsActionHandler()
);
Another possibility is to inverse the order of definition of your routes and constrain the default route:
public static void RegisterRoutes(RouteCollection routes)
{
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Default",
"{controller}/{action}/{id}",
new { controller = "Home", action = "Index", id = UrlParameter.Optional },
new { controller = "^((?!JsAction).)*$", action = "^((?!JsAction).)*$" }
);
routes.Add("JsActionRoute", JsAction.JsActionRouteHandlerInstance.JsActionRoute);
}
Upvotes: 1