Dave New
Dave New

Reputation: 40032

MVC Hierarchical Routing

Are the following routes possible (and does it even make "MVC-sense") with ASP.NET MVC 5:

Organisations/3/Employees/7/Edit

Description: From organisation of id 3, editing employee with id 7.

Organisations/3/Employees/Create

Description: Create a new employee for organisation 3.

Employees belong to organisations (they cannot exist without an organisation), which is why I like the hierarchical URL structure. It resembles that of resources in a RESTful API design.

Upvotes: 0

Views: 988

Answers (1)

Anthony Shaw
Anthony Shaw

Reputation: 8166

Yes, I create a variant of these routes in most of my admin applications, they almost feel "fluent" the way they read.

Here is a quick sample of my route definitions how I would lay it out.

_routeCollection.MapRoute(null, 
  "Organisations/{organisationId}/Employees/{id}/edit", 
  new { controller = "Employee", action = "Edit" });

_routeCollection.MapRoute(null, 
  "Organisations/{organisationId}/Employees/create", 
  new { controller = "Employee", action = "Create" });

Then you employee controller actions Edit/Create would accept the organisationId parameter along with any other needed parameters to invoke those actions. I generally add this next route to handle the details of an object

_routeCollection.MapRoute(null, 
  "Organisations/{organisationId}/Employees/{id}", 
  new { controller = "Employee", action = "Detail" });

To create an Html.ActionLink you would call @Html.ActionLink("Employee", "Edit", new { organisationId = 2, id = 10});

Upvotes: 1

Related Questions