C#3.5 MVC2 routing skip optional param

让人想犯罪 __ 提交于 2019-12-13 20:34:05

问题


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}.


回答1:


DataWarehouse/Distribution/{category}/{serialNo}

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




回答2:


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}"}  
);



回答3:


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.



来源:https://stackoverflow.com/questions/3187456/c3-5-mvc2-routing-skip-optional-param

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!