vincentw56
vincentw56

Reputation: 545

ASP.NET MVC ActionLink Issue with Custom Routes

I've been trying to get a couple of custom routes working with no luck. I have two pages for my automotive app. The first page shows a list of vehicles. When the user clicks the links generated on this page it takes them to the product list page. The problem is this page doesn't generate the links properly.

Here is the routes:

            routes.MapRoute(
                "Select_Vehicle",
                "Select_Vehicle/{id}/{make}",
                new { controller = "Select_Vehicle", action = "Index", id = UrlParameter.Optional, make = UrlParameter.Optional });

            routes.MapRoute(
                "Products",
                "Products/{id}/{make}/{model}",
                new { controller = "Products", action = "Index", id = UrlParameter.Optional, make = UrlParameter.Optional, model = UrlParameter.Optional });

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

The Select_Vehicle page should generate links like this:

/products/horns/dodge/dakota

but what I get is this:

/Products/Index/horns?make=dodge&model=Dakota

It just doesn't work properly. Also, I don't understand why "Index" also shows since it is the default.

I've tried both ActionLink and RouteLink:

@Html.RouteLink(model, new { Controller = "Products", id = Model.CategoryName, make = Model.CurrentMake, model = model })
@Html.ActionLink(model, "Index", "Products", new { id = Model.CategoryName, make = Model.CurrentMake, model = model }, null)

This is driving me crazy.

Upvotes: 1

Views: 1256

Answers (3)

vincentw56
vincentw56

Reputation: 545

Well, I figured out the problem. You can have more than one UrlParameter.Optional, but there is an issue. It is a bug or feature depending on how Microsoft wants to position it.

The issue is the the make was empty which caused a problem when it was building the URL. You can find more information here:

http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx

Thanks for all the suggestions and help.

Upvotes: 0

Jack
Jack

Reputation: 2660

Your code should work. I've tested your routes with a fresh project and this is what I got. Do you have anything else in your route configuration?

http://localhost:60599/Products/horns/dodge/dakota

I am using asp.net MVC 3

Upvotes: 0

tvanfosson
tvanfosson

Reputation: 532465

ASP.NET MVC only supports a single optional parameter. Update your routes to give make and model a default rather than making them optional. You might also need to use the overload on RouteLink that takes the route name so that it chooses the correct route.

@Html.RouteLink(model, "Products", new 
 {
     id = Model.CategoryName,
     make = Model.CurrentMake,
     model = model
 })

Upvotes: 2

Related Questions