C#3.5 MVC2 routing skip optional param
Here I have:
routes.Map开发者_JS百科Route(
"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}
.
DataWarehouse/Distribution/{category}/{serialNo}
Only the last parameter can be optional. In this example category cannot be optional for obvious reasons.
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}"}
);
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.
精彩评论