2013-09-05 50 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