2013-09-05 49 views
0

我有這樣路由可選布爾值

public ActionResult DoSomething(bool special = false) 
{ 
    // process the special value in some special way... 
    return View(); 
} 

我要訪問使用僅由特殊的標記不同的兩種不同的鏈接此操作的MVC控制器操作方法,我想通過標誌作爲一個人類可讀的路線價值。 更確切地說,這些鏈接應該是這樣的:

SomeController/DoSomething 
SomeController/DoSomething/Special 

目前我已經創建動作鏈接:

@Html.ActionLink("Just do it", "DoSomething", "SomeController") 
@Html.ActionLink("Do it in a special way", "DoSomething", "SomeController", new { special = true}, null) 

這個代碼生成像這樣的鏈接:

SomeController/DoSomething/Special 
SomeController/DoSomething?special=True 

顯然,我需要一個特殊的路線,第二個鏈接變成SomeController/DoSomething/Special但我所有的嘗試都失敗了,因爲在一次MapRoute嘗試中,它忽略了我的特殊fl ag,在另一個MapRoute嘗試它使兩個鏈接都變爲SomeController/DoSomething/Special,儘管我沒有爲第一個ActionLink指定特殊路由值(我猜它只是從路由中選取它)。

將bool special映射到URL SomeController/DoSomething/Special並使ActionLink生成正確鏈接的正確方法是什麼?

回答

0

假設默認路由的設置,你可能會產生這樣的錨:

@Html.ActionLink(
    "Just do it", 
    "DoSomething", 
    "SomeController" 
) 

@Html.ActionLink(
    "Do it in a special way", 
    "DoSomething", 
    "SomeController", 
    new { id = "Special" }, 
    null 
) 

和你的控制器動作,現在可能是這樣的:

public ActionResult DoSomething(string id) 
{ 
    bool special = !string.IsNullOrEmpty(id); 

    // process the special value in some special way... 
    return View(); 
} 
0

使用這樣的事情在你的路線配置

routes.MapRoute(
       name: "Default", 
       url: "{controller}/{action}/{Category}/{Name}", 
       defaults: new { controller = "Account", action = "Index", Category= UrlParameter.Optional, Name= UrlParameter.Optional } 

詳情請查看http://www.dotnetcurry.com/ShowArticle.aspx?ID=814