So with typecode my route doesn't work and with id it does. What am I doing wrong?
The problem is you no doubt still have the default route being mapped before your custom route i.e.
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
Which means anything that matches a url similar to "controller/action/id" will be parsed by the default route, not your custom one. The fact that this route does not recognise typecode
as an expected parameter means it's treated as a query string parameter (hence ?typecode=
).
If you want to pick up the typecode
be more specific with which controller you want to map it to and put this route before the default one i.e.
routes.MapRoute(
"CategoryItem",
"{controller}/Categories/{typecode}",
new { controller = "Search", action = "Categories", typecode = UrlParameter.Optional }
);
routes.MapRoute(
"Default", // Route name
"{controller}/{action}/{id}", // URL with parameters
new { controller = "Home", action = "Index", id = "" } // Parameter defaults
);
This would constrain any urls which start like controller/Categories/
to only accept a typecode
and not an id
- this should result in your URL forming as Search/Categories/12345
. You could constraint this further by controller if you really wanted to (just replace {controller}
with Search
in the route).
However, I don't see any real benefits of doing this considering you don't actually show typecode
in the URL anywhere. I could understand if you were looking to show the url as Search/Categories?typecode=12345
as it's probably a bit more descriptive than id
. Personally, I would leave your default route as is and change your action link to:
@Html.ActionLink("Ga", "Categories", "Search", new { id = 16860 }, null)
It will give you the same result.
Update
Based on your update, the only thing I can think of is you aren't specifying a default value in the route so perhaps it's not picking the parameter correctly, try:
routes.MapRoute("TypeCode",
"Search/Categories/{typecode}",
new { controller = "Search", action = "Categories", typecode = "" }
);