路由可选的bool值

时间:2013-09-05 13:17:25

标签: asp.net-mvc routing

我有像这样的MVC控制器动作方法

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

我想使用两个不同的链接来访问此操作,这两个链接只有特殊标志不同,我想将该标志作为人类可读的路由值传递。 更确切地说,链接应如下所示:

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尝试中它忽略了我的特殊标志,而在另一次MapRoute尝试中它使两个链接变为{ {1}}虽然我没有为第一个ActionLink指定特殊路由值(它只是从路由中选择它,我猜)。

将bool SomeController/DoSomething/Special映射到网址special并使ActionLink生成正确的链接的正确方法是什么?

2 个答案:

答案 0 :(得分: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();
}

答案 1 :(得分: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