0

I'd like to define one MapRoute which can map two different routes to one action.

I have an action to create an address:

public class AddressesController : BaseController
{
    public ActionResult Create()
    {
        ...
    }
}

Following two routes should map to the action:

/Addresses/Create -> To create a new address
/Projects/3/Addresses/Create -> To create a new address to the project with the id = 3

I tried the following MapRoute config to accomplish this, but didn't work:

routes.MapRoute(
    name: "CreateAddress",
    url: "{projects}/{projectId}/{controller}/{action}",
    defaults: new { projects = "", projectId = UrlParameter.Optional, controller = "Addresses", action = "Create" },
    constraints: new { project = "(Projects)?" });

With this config the route /Projects/3/Addresses/Create is working but not /Addresses/Create.

tschan
  • 112
  • 2
  • 11

1 Answers1

1

You can't have both ways working in the same route.

You need to specify only the extra route, because ASP.NET MVC comes with a default one that will make sure that /Addresses/Create will work:

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}/{id}",
    defaults: new { controller = "Home", action = "Index", id = UrlParameter.Optional });

For the /Projects/3/Addresses/Create put this before the above route:

routes.MapRoute(
    name: "CreateAddress",
    url: "Projects/{projectId}/{controller}/{action}",
    defaults: new { controller = "Addresses", action = "Create" });
Cristian Szpisjak
  • 2,429
  • 2
  • 19
  • 32