4

I have a custom route inside an area:

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

Before adding the Route and RouteArea attributes, I accessed this action through the following route:

~/MyArea/MyController/MyAction

Now that I added this attributes, I am able to access it just through this:

~/my-action

I used to have an ActionLink which was pointing to this action and it looked like this:

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

Now this ActionLink is no longer working. How can I fix it?

6
  • 1
    You ActionLink would never have worked - you controller is named MyController so it would have need to be @Html.ActionLink("Link To My Action", "MyAction", "My", new { Area = "MyArea" }, new { }) Commented Nov 30, 2015 at 8:06
  • Sorry, this is just an example and I did a mistake when changing the names of the Area, the Controller and the Action. In my real code this is correct and I also fixed it in my question. Commented Nov 30, 2015 at 8:23
  • 1
    You are using Attribute Routing, have you initialized this feature in the RouteConfig.cs file like this: routes.MapMvcAttributeRoutes() in the RegisterRoutes method? Commented Nov 30, 2015 at 8:28
  • Yes, I have initialized it. Commented Nov 30, 2015 at 8:44
  • I had the conflict earlier when using both Traditional Routing and Attribute Routing - perhaps try to remove the Traditional one if you have any traces of it, and just try to go with Attributes? Commented Nov 30, 2015 at 9:12

1 Answer 1

10

I came up with the following solution:

I added a Name to the route that I created.

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

And then I used the RouteLink helper method, instead of the ActionLink one like this:

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

So, the first parameter of the RouteLink method is the text of the link and the second one is the name of the route - the same name that you've put in the Route attribute.

Sign up to request clarification or add additional context in comments.

2 Comments

For me, it was sufficient to just use @Url.RouteUrl("CustomRoute")
Adding an <a> with @Url.RouteUrl helped me mout thanks Alex

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.