ElHaix
ElHaix

Reputation: 12996

MVC3 Routes - how to ensure a route with a specific value takes precedence?

Given the following two defined routes:

        routes.MapRoute(name: "CityCategoryPage", url: "{city}-{state}/{categoryName}/__c/", defaults: new { controller = "Home", action = "GeoSubCategories" });
        routes.MapRoute(name: "CityStateCategoryResults", url: "{city}-{state}/{categoryName}/{searchTerm}/{pageNumber}/{pageSize}", defaults: new { controller = "Results", action = "SearchCityStateCategory", pageNumber = UrlParameter.Optional, pageSize = UrlParameter.Optional });

If I remove the second route, I get the expected action of seeing the results on the home page. However with the second route present, I'm always forwarded to a results page.

I have an idea as to why this is happening: "_c" is still seen as an optional parameter which matches the optional condition for the second route, but not sure how to get this to work. I would prefer not to append the "_c" to the URL - also wondering if there is another way around this?

Thanks.

Upvotes: 0

Views: 232

Answers (1)

If I understand you correctly you want the frontpage to be displayed if no search term is provided?

If so, try to match the route with the optional searchTerm first, and default to the home page route if no searchTerm is present, like so:

routes.MapRoute(name: "CityStateCategoryResults", url: "{city}-{state}/{categoryName}/{searchTerm}/{pageNumber}/{pageSize}", defaults: new { controller = "Results", action = "SearchCityStateCategory", pageNumber = UrlParameter.Optional, pageSize = UrlParameter.Optional });
routes.MapRoute(name: "CityCategoryPage", url: "{city}-{state}/{categoryName}/", defaults: new { controller = "Home", action = "GeoSubCategories" });

Upvotes: 1

Related Questions