【问题标题】:ActionLink with Attribute Routing in MVC 5在 MVC 5 中使用属性路由的 ActionLink
【发布时间】:2014-09-07 07:10:14
【问题描述】:

我在使用 MVC 5 中的 ActionLink 时遇到问题。

@Html.ActionLink("View Commissions", "/" + item.Id.ToString, "Commissions") 
@Html.ActionLink("View Commissions", "Index", "Commissions", New With {Key .payRollId = item.Id}, Nothing)

这两个 ActionLink 应该完成同样的事情,但我更喜欢使用第二个。不幸的是,它们产生了不同的 URL。第一个创建http://mysite/Commissions/3。第二个创建http://mysite/Commissions?payRollId=3

在我的佣金控制器中,我有以下代码:

    ' GET: Commissions/5
    <Route("Commissions/{payRollId:min(1)}")>
    Async Function Index(ByVal payRollId As Integer?) As Task(Of ActionResult)
        If IsNothing(payRollId) Then
            Return New HttpStatusCodeResult(HttpStatusCode.BadRequest)
        End If

        Return View(Await ...query...).ToListAsync)
    End Function

这成功处理了第一个 ActionLink 的 URL。第二个导致 404 错误。我没有任何其他 RouteAttributes 或用于佣金的映射路线。根据这个attribute routing article,第二个 ActionLink 应该创建成功处理请求的漂亮 URL(无查询字符串)。

我错过了什么?如何让第二个 ActionLink 生成正确的 URL (Commissions/3) 以匹配 RouteAttribute?

【问题讨论】:

    标签: vb.net asp.net-mvc-5 asp.net-mvc-routing actionlink attributerouting


    【解决方案1】:

    编辑

    这应该会产生所需的路线:

    <a href="~/Commissions/@item.Id">View Commissions</a>
    

    这假设您已启用基于属性的路由,如下所示:

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
    
            routes.MapMvcAttributeRoutes();
    
            routes.MapRoute(
                "Default", 
                "{controller}/{action}/{id}", 
                new { controller = "Home", action = "Index", id = UrlParameter.Optional });
        }
    }
    

    【讨论】:

    • 感谢您的帮助。不幸的是,这会产生与 RouteAttribute 不匹配的 http://mysite/Commissions/Index/3 并导致 404 错误。也许我应该在 Controller 中创建另一个 Action,但这似乎是多余的。如果我选择该选项,我只需将当前的 RouteAttribute 更改为包含 Index
    • 那你想要的完整路线是什么?我假设您的控制器称为 CommissionsController。不是这样吗?
    • 我想要的完整路线是http://mysite/Commissions/{payRollId},其中payRollId 是一个整数。尽管 Action 是“Index”,但它在实际 URL 中被省略了。控制器不称为 CommissionsController(它要长得多,并且是使用脚手架选项自动生成的)。
    • 编辑我的答案以适应非常规路线。据我所知,@Html.ActionLink 助手对非常规(即基于属性)的路线没有帮助。可以想象创建自己的助手来完成这项工作,但利用 Razor 通过 ~/ 处理基本路由并直接使用锚标签可能更快。
    【解决方案2】:

    我有一个部分解决方案。我使用了控制器代码,发现将 RouteAttribute 更改为 &lt;Route("Commissions/{payRollId:min(1)?}")&gt;(注意末尾的 ?)允许它处理第二个 URL。

    我仍在研究如何使用第二个 ActionLink 生成漂亮的 URL。如果我解决了,我会更新这个答案。

    【讨论】:

      猜你喜欢
      • 2016-11-01
      • 2013-10-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多