views:

68

answers:

3

Here I have:

routes.MapRoute(
    "test", // Route name
    "DataWarehouse/Distribution/{category}/{serialNo}",
    new { controller = "DataWarehouse", 
          action = "Distribution", 
          category= UrlParameter.Optional, 
          serialNo = UrlParameter.Optional } 
);

Category and serialNo are both optional params. When the routing is like: DataWarehouse/Distribution/123, it always treat 123 as the value for category.

My question is how I can make it to know the 1st param could be either category or serialNo, i.e. DataWarehouse/Distribution/{category} and DataWarehouse/Distribution/{serialNo}.

A: 
DataWarehouse/Distribution/{category}/{serialNo}

Only the last parameter can be optional. In this example category cannot be optional for obvious reasons.

Darin Dimitrov
A: 

If you know what your parameters will look like you can add a route constraint to differentiate both routes

Ex if your serial are 1234-1234-1234 and your category are not like this:

routes.MapRoute(
    "serialonly", // Route name
    "DataWarehouse/Distribution/{serialNo}",
    new { controller = "DataWarehouse", 
          action = "Distribution", 
          category= UrlParameter.Optional, 
          serialNo = UrlParameter.Optional },
    new{serialNo = @"\d{4}-\d{4}-\d{4}"} 
);

routes.MapRoute(
    "test", // Route name
    "DataWarehouse/Distribution/{category}/{serialNo}",
    new { controller = "DataWarehouse", 
          action = "Distribution", 
          category= UrlParameter.Optional, 
          serialNo = UrlParameter.Optional },
    ,
    new{serialNo = @"\d{4}-\d{4}-\d{4}"}  
);
Gregoire
A: 

I had a similar problem, i was trying to route based on data ({year}/{month}/{day}) where month or day could be optional. What I found was that I couldn't do it with a single route. So I solved it by using 3 routes, from generic to specific (year, year and month, year and month and day). I am not completely pleased with it, but it works.

So provided that you are looking for DataWarehouse/Distribution/{category} and DataWarehouse/Distribution/{category}/{serialNo} routes, i think this would work for you.

Jonathan Bates