【问题标题】:Routing optional bool values路由可选布尔值
【发布时间】:2013-09-06 02:36:44
【问题描述】:

我有一个像这样的 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 映射到 URL SomeController/DoSomething/Special 并使 ActionLink 生成正确链接的正确方法是什么?

【问题讨论】:

    标签: asp.net-mvc routing


    【解决方案1】:

    假设设置了默认路由,您可以像这样生成锚点:

    @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();
    }
    

    【讨论】:

      【解决方案2】:

      在你的路由配置中使用类似的东西

      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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2019-02-23
        • 2011-10-14
        • 1970-01-01
        • 2017-07-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多