Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an ActionLink to a custom route in ASP.NET MVC?

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?

like image 428
Yulian Avatar asked Jan 07 '23 02:01

Yulian


1 Answers

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.

like image 178
Yulian Avatar answered Jan 29 '23 23:01

Yulian