【问题标题】:How to create an ActionLink to a custom route in ASP.NET MVC?如何在 ASP.NET MVC 中创建指向自定义路由的 ActionLink?
【发布时间】:2016-03-03 19:30:00
【问题描述】:

我在一个区域内有一条自定义路线:

[RouteArea("MyArea")]  
public class MyController: Controller
{
    [Route("~/my-action")]
    public ActionResult MyAction()
    {
        return View();
    }
}

在添加 RouteRouteArea 属性之前,我通过以下路由访问了此操作:

~/MyArea/MyController/MyAction

现在我添加了这个属性,我可以通过这个来访问它:

~/my-action

我曾经有一个 ActionLink 指向这个动作,它看起来像这样:

@Html.ActionLink("Link To My Action", "MyAction", "My", new { Area = "MyArea" }, new { })

现在这个 ActionLink 不再起作用了。我该如何解决?

【问题讨论】:

  • ActionLink 永远不会工作 - 你的控制器被命名为 MyController 所以它必须是 @Html.ActionLink("Link To My Action", "MyAction", "My", new { Area = "MyArea" }, new { })
  • 对不起,这只是一个例子,我在更改区域、控制器和动作的名称时犯了一个错误。在我的真实代码中这是正确的,我也在我的问题中修复了它。
  • 你正在使用Attribute Routing,你有没有在RouteConfig.cs文件中这样初始化这个特性:routes.MapMvcAttributeRoutes()RegisterRoutes方法中?
  • 是的,我已经初始化了。
  • 我之前在同时使用 Traditional RoutingAttribute Routing 时遇到了冲突 - 如果您有任何痕迹,可以尝试删除 Traditional,然后尝试使用 Attributes ?

标签: asp.net-mvc routing asp.net-mvc-5


【解决方案1】:

我想出了以下解决方案:

我为我创建的路线添加了一个名称。

[Route("~/my-action", Name = "CustomRoute")]
public ActionResult MyAction()

然后我使用了 RouteLink 辅助方法,而不是像这样的 ActionLink:

@Html.RouteLink("Link To My Action", "CustomRoute")

所以,RouteLink 方法的第一个参数是链接的文本,第二个参数是路由的名称 - 与您在 Route 属性中输入的名称相同。

【讨论】:

  • 对我来说,只需使用@Url.RouteUrl("CustomRoute")
  • 用@Url.RouteUrl 添加一个 帮助我感谢Alex
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-10-07
  • 2021-07-12
  • 2011-04-02
  • 2020-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多