Search code examples
asp.net-mvcrazorasp.net-mvc-5attributerouting

Create URL in Razor View for Attribute Route containing parameters


I have the controller below with a route specified which contains a parameters matching the overload on the action.

public class OrganisationsController : Controller
{
    [HttpGet]
    [Route("organisations/{id}/employees")]
    public ActionResult Employees(int id)
    {
        //  Some code here
    }
}

I'm trying to create the URL in a Razor View using @Html.ActionLink to match the route specified on the controller, for example localhost:55416/Organisations/2/Employees, but I've not been able to get it working.

The closest I've been able to get is localhost:55416/Organisations/Employees/2 which doesn't work as the route is wrong, or localhost:55416/Organisations/Employees?id=2 which actually works as the Employees action on the Organisations controller is hit, but then it's just a query string then which negates the purpose of adding the [Route("organisations/{id}/employees")] route in the first place.

All the examples and posts I've been able to find on the interwebs deal with the parameter being at the end, for example [Route("organisations/employees/{id}")], and not in between the controller and the action.

I haven't bothered by trying to add custom route to the RouteConfig as in my mind the URL is the starting point which needs to be correct first according to the Route specified on the controller, or am I wrong here?

Is there a way for me to generate the URL the way I want it to using ActionLink, or is there another way I need to go about doing this?


Solution

  • Credit should go to Sam, the ActionLink he provided was correct, the reason it didn't work when I tried it was because I did not add the routes.MapMvcAttributesRoutes(); line to the RouteConfig.cs of the project in which I was trying to create the URL, after adding it the expected localhost:55416/Organisations/2/Employees url gets generated by the @Html.ActionLink("Employees", "Employees", "Organisations", new { id = item.Id }, null) action link.

    public class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            routes.IgnoreRoute("{resource}.axd/{*pathInfo}");
            routes.MapMvcAttributeRoutes();
    
            routes.MapRoute(
                name: "Default",
                url: "{controller}/{action}/{id}",
                defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional }
            );
        }
    }