Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

html.routelink does not go to specified route

I have bunch of routes defined as:

routes.MapRoute(
                name: "ID",
                url: "{category}/{subcategory}/{lowercategory}/{lowercategory1}/{id}/{ignore}",
                defaults: new { controller = "Home", action = "Index", ignore = UrlParameter.Optional }
            );

            routes.MapRoute(
                name: "LowerCategory1",
                url: "{category}/{subcategory}/{lowercategory}/{lowercategory1}",
                defaults: new { controller = "Home", action = "Index" }
            );

            routes.MapRoute(
                name: "LowerCategory",
                url: "{category}/{subcategory}/{lowercategory}",
                defaults: new { controller = "Home", action = "Index" }
            );

            routes.MapRoute(
                name: "Subcategory",
                url: "{category}/{subcategory}",
                defaults: new { controller = "Home", action = "Index" }
            );

            routes.MapRoute(
                name: "Category",
                url: "{category}",
                defaults: new { controller = "Home", action = "Index" }
            );

            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );

Now I used routeLink to access default route but its not working.

@Html.RouteLink("Create Ad", "Default", new { controller="Electronics",action="Details" })

The request goes to home contoller index function. What I am doing wrong. How to use routeLink so that request should go to default route.

like image 253
Irfan Yusanif Avatar asked Oct 31 '22 20:10

Irfan Yusanif


1 Answers

I had this problem too. It seems that the code calls the RouteLink overload with signature

RouteLink(string linkText, object routeValues, object htmlAttributes)

Which means that routeName is never set with this overload and most likely you get an anchor element with an empty href attribute or a link generated with default controller and action, because routeValues is also not set to what you expect.

We want to actually call this overload instead

RouteLink(string linkText, string routeName, object routeValues)

Which can be ensured by using named arguments like so:

@Html.RouteLink("Create Ad", routeName: "Default", routeValues: new { controller="Electronics",action="Details" })
like image 164
Mellow Avatar answered Nov 15 '22 08:11

Mellow