I have this route defined:
routes.MapRoute(
"Details", // Route name
"{home}/{details}/{id}/{name}", // URL with parameters
new
{
controller = "Home",
action = "Details",
id = UrlParameter.Optional,
name = UrlParameter.Optional
} // Parameter defaults
);
The ActionLink:
@Html.ActionLink("Show Details", "Details", "MyController", new { id = 1, name ="a" })
The actionlink results in /Home/Details/1?name=a
I am after /Home/List/1/a
A wild guess :
probably your route was registered after the default route. Put it as first route inside your global.asax then it will work.
Like below :
public static void RegisterRoutes(RouteCollection routes) {
routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
routes.MapRoute(
"Details", // Route name
//Put action instead of details
"{home}/{action}/{id}/{name}", // URL with parameters
new
{
controller = "Home",
action = "Details",
id = UrlParameter.Optional,
name = UrlParameter.Optional
} // Parameter defaults
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);
}
UPDATE
@Simon is correct, but you can use another way if you want.
In order for the route to work only for one action method, use following code.
Create a constraint as follows :
public class EqualConstraint : IRouteConstraint {
private string _match = String.Empty;
public EqualConstraint(string match) {
_match = match;
}
public bool Match(System.Web.HttpContextBase httpContext, Route route, string parameterName, RouteValueDictionary values, RouteDirection routeDirection) {
return string.Equals(values[parameterName].ToString(), _match);
}
}
And then change your route like below :
routes.MapRoute(
"Details", // Route name
//Put action instead of details
"{home}/{action}/{id}/{name}", // URL with parameters
new
{
controller = "Home",
action = "Details",
id = UrlParameter.Optional,
name = UrlParameter.Optional
}, // Parameter defaults
new {
controller = new EqualConstraint("Home"),
action = new EqualConstraint("Details")
}
);
Your route definition should be like this:
routes.MapRoute(
"Details", // Route name
"{controller}/{action}/{id}/{name}", // URL with parameters
new
{
controller = "Home",
action = "Details",
id = UrlParameter.Optional,
name = UrlParameter.Optional
} // Parameter defaults
);
Also you should use the proper overload:
@Html.ActionLink(
"Show Details", // linkText
"Details", // action
"MyController", // controller
new { id = 1, name = "a" }, // routeValues
null // htmlAttributes
)
Notice the null
at the end.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With