c# - ASP.NET MVC 4 RouteLink 不工作

标签 c# asp.net-mvc routes asp.net-mvc-4

在我的 MVC 4 应用程序中,我使用了 Area,这是我的路线:

context.MapRoute(
                "Service_AcceptBid",
                "Service/{controller}/{action}/{id}/{accept}",
                new { area = "Service", controller = "Project", action = "AcceptBid", id = UrlParameter.Optional, accept = UrlParameter.Optional }
            );

context.MapRoute(
                "Service_BidNegotiation",
                "Service/{controller}/{action}/{id}/{bid}",
                new { area = "Service", controller = "Project", action = "Negotiations", id = UrlParameter.Optional, bid = UrlParameter.Optional }
            );

我将这些链接放在我的 .cshtml 页面上:

<div dir="ltr">
       @Html.RouteLink("Accept", "Service_AcceptBid", new { controller = "Project", action = "AcceptBid", Id = item.ProjectId, Accept = item.Id })
       @Html.RouteLink("Negotiate", "Service_BidNegotiation", new { controller = "Project", action = "Negotiations", Id = item.ProjectId, Bid = item.Id })
</div>

当第一个链接被点击时,AcceptBid Controller 被调用并且它的参数(Id,Accept)被设置为 url 值。但是当我点击第二个链接时, Controller 方法中的 Id 参数已设置,但第二个参数 (Bid) 为空。

为什么会这样?
我该怎么做才能解决这个问题?

谢谢。

最佳答案

解释问题

输出路由(链接生成)很好。问题在于传入路由。当您单击应由第一个路由处理的第二个链接时,它实际上由第一个路由处理,因为它符合其定义。

可能的解决方案(没有硬编码操作)

您所要做的就是为第一个路由提供额外的约束,以防止它处理应由第二个路由处理的请求。

检查我的以下代码更改,我在 action 参数上添加了路由约束以提供可能的值:

context.MapRoute(
    "Service_AcceptBid",
    "Service/{controller}/{action}/{id}/{accept}",
    new { area = "Service", controller = "Project", action = "AcceptBid", id = UrlParameter.Optional, accept = UrlParameter.Optional },
    new { action = "AcceptBid|RejectBid|..." }
);

context.MapRoute(
    "Service_BidNegotiation",
    "Service/{controller}/{action}/{id}/{bid}",
    new { area = "Service", controller = "Project", action = "Negotiations", id = UrlParameter.Optional, bid = UrlParameter.Optional }
);

与为每个单独的操作创建静态路由定义相比,这将使您的路由更加动态。

关于c# - ASP.NET MVC 4 RouteLink 不工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13817653/

相关文章:

c# - 混合使用同一类中的已实现方法和模拟方法

c# - 为什么我不能从派生类的 XML 文档注释标记中引用基类中的可访问成员?

AngularJS在路由之间传递范围

c# - 尽管 TransactionScopeOption.Suppress 嵌套事务回滚

c# - 如何在 Windows 10 上调试丢失的 dll

json - ASP MVC 区域和 JSON POST

asp.net-mvc - 模板 Razor 委托(delegate) - 交替行

c# - ASP.NET MVC : How does a controller distingush between parameters in the URL and sent by POST

asp.net-mvc - 堆栈溢出问题路由

android - 在Android上, 'Sign in to network'使用奇怪的IP路由?