0

我有一个像这样的 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 尝试中,SomeController/DoSomething/Special尽管我没有指定特殊路线值,但它使两个链接都成为对于第一个 ActionLink(我猜它只是从路线中拾取的)。

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

4

2 回答 2

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();
}
于 2013-09-05T13:43:48.947 回答
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

于 2013-09-05T13:55:08.500 回答