Search code examples
asp.netasp.net-mvc-3url-routingurl.action

ASP.NET MVC 3 URL.Action mapped to incorrect Route


I have these two routes configured in my app:

routes.MapRoute(
             "PromotionModel-test", // Route name
             "testSpecifications", // URL with parameters
             new { controller = "test", action = "Brochure", modelName = "test", groupID = 0 } // Parameter defaults
         );

routes.MapRoute(
          "", // Route name
          "{controller}/{action}/{id}", // URL with parameters
          new { groupID = 0, controller = "Home", action = "List", id = UrlParameter.Optional, CatID = 0 },
          new {controller = @"\w{3,}"}
        );

When I call

 @Url.Action("Brochure", "test")

the url it generated is "/testSpecifications" instead of "test/Brochure". When I explicitly do

@Url.Action("Brochure", "test", new { modelName = string.Empty })

Then it will produce the correct result.

I know there is segment variable reuse scenario, but how does it apply here? What's the logic behind the scene?

Updates

What I want to achieve here is to simply produce the URL I had above without having to explicitly set any parameter values.

Imagine you started developing a website, where it didn't require any parameters. Later on, you have notice you might need to add several addition parameters, in the example above, the new parameter added is "modelName". And then you client request to map the "testSpecifications" to map to the specific page like the one above.

We definitely don't want to go back to update all the Url.Action to set the default values for each of them. What approach would you take to deal with this?

Hope this make sense....


Solution

  • As Kasper mentioned above, with the route below, the value in the "modelName" is been used as an "default" value instead of a constrain to check against.

    routes.MapRoute(
                 "PromotionModel-test", // Route name
                 "testSpecifications", // URL with parameters
                 new { controller = "test", action = "Brochure", modelName = "test", groupID = 0 } // Parameter defaults
             );
    

    So the key to resolve the issue is to make it a constrain rather than just default value. Here is the correct route configuration that resolves my issue.

    I was surprised myself when seen it mapping correctly for both incoming request(localhost/testSpecifications) and url generation (Url.Action("Brochure,Test")...

     routes.MapRoute(
                     "PromotionModel-test", // Route name
                     "testSpecifications", // URL with parameters
                     new { controller = "test", action = "Brochure", modelName = "test", groupID = 0 },
                   new { modelName="test"}
                 );