如何在ASP.NET MVC中创建ActionLink到自定义路由?

时间:2015-11-30 08:02:19

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

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

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

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

~/MyArea/MyController/MyAction

现在我添加了这些属性,我只能通过它来访问它:

~/my-action

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

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

现在这个ActionLink不再有效了。我该如何解决?

1 个答案:

答案 0 :(得分:6)

我提出了以下解决方案:

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

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

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

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

因此,RouteLink方法的第一个参数是链接的文本,第二个参数是路径的名称 - 与您在Route属性中放置的名称相同。