2014-02-11 64 views
0

我在RouteConfig.cs中創建了一個如下所示的新路由。帶可選參數的MVC4路由問題

routes.MapRoute("Edit_Personal", 
       "Edit/Personal/{userID}/{refKey}/{houseID}", 
       new {controller = "Edit", action = "Personal", 
         userID = UrlParameter.Optional, 
         refKey = UrlParameter.Optional, 
         houseID = UrlParameter.Optional }); 

這條線路工作正常,如果我像傳:

Edit/Personal/78887/abcd/ 

UserID = 78887 
RefKey = abcd 
HouseID = null 

但是,如果RefKey不會傳遞(它是可選的),但HouseID傳遞,我得到這個作爲結果(網址):

Edit/Personal/78887//88881 <--- Notice the two slashes between the numbers. 

UserID = 78887 
RefKey = 88881 
HouseID = null 

結果我的預期是:

UserID = 78887 
RefKey = null 
HouseID = 88881 

如果您注意到,RefKey應該爲NULL,但是它將HouseID綁定到RefKey參數中。

有沒有辦法解決這個問題?我錯過了什麼嗎?

+1

你可以用一個問號做到這一點,是這樣的:'」編輯/個人/ {用戶ID}/{refKey?}/{} houseID「' –

回答

1

您需要定義像下面多條路線:

routes.MapRoute(
    "WithAll", 
    "{controller}/{action}/{UserID}/{RefKe}/{HouseID}", 
    new{ controller = "Edit",action = "Personal"}); 

routes.MapRoute(
    "WithoutRefke", 
    "{controller}/{action}/{UserID}/{HouseID}", 
    new{controller = "Edit",action = "Personal"}); 

routes.MapRoute(
    "WithoutRefkeAndHouseID", 
    "{controller}/{action}/{UserID}", 
    new{controller = "Edit",action = "Personal",UserID= UrlParameter.Optional}); 

看看下面的鏈接瞭解詳情: http://haacked.com/archive/2011/02/20/routing-regression-with-two-consecutive-optional-url-parameters.aspx/