Dan
Dan

Reputation: 1575

MVC routing more than one controller

I am using MVC 4.0 and I am trying to add a route for each controller.

Well, my first controller is called CustomersController. The route that I've added is:

    routes.MapRoute(
        name: "Customer",
        url: "{controller}/{action}/{IdCustomer}",
        defaults: new { controller = "Customers", action = "Index", IdCustomer = UrlParameter.Optional }
    );

When I am running the application, I get the following links in the Index page(List):

http://localhost:6838/Customers/Create/5
http://localhost:6838/Customers/Edit/5
http://localhost:6838/Customers/Details/5
http://localhost:6838/Customers/Delete/5

Ok, great! It's what I am looking for, but, now start my problem. I added another controller, called ItemsController (with the same actions - Create/Edit/Details/Delete) then I tried to add the same route:

    routes.MapRoute(
        name: "Item",
        url: "{controller}/{action}/{IdItem}",
        defaults: new { controller = "Items", action = "Index", IdItem = UrlParameter.Optional }
    );

But now the result is different... I am getting the following links:

    http://localhost:6838/Items/Create?IdItem=1
    http://localhost:6838/Items/Edit?IdItem=1
    http://localhost:6838/Items/Detail?IdItem=1
    http://localhost:6838/Items/Delete?IdItem=1

WHY.. WHY :'( it isn't working? Why it's working only for the first route and not for the new one just added?!

Best regards, Dan

Upvotes: 1

Views: 972

Answers (1)

Brad Christie
Brad Christie

Reputation: 101594

To give a synopsis of my answer, your routes are too vague. You need to be more specific to get a better result (especially if you're not using the route by name). I would go for something like the following:

routes.MapRoute(
    name: "Customers",
    url: "Customers",
    defaults: new { controller = "Customers", action = "Index" }
);
routes.MapRoute(
    name: "CustomerDetails",
    url: "Customer/{IdCustomer}",
    defaults: new { controller = "Customers", action = "Details", IdItem = UrlParameter.Optional }
);
routes.MapRoute(
    name: "CustomerEdit",
    url: "Customer/{IdCustomer}",
    defaults: new { controller = "Customers", action = "Edit", IdItem = UrlParameter.Optional }
);
/* and so on (then move on to Items) */

Now you can reference them by name and also eliminate a lot of the rudimentary information you normally provide (like action and controller details). It also makes updating a link easier down the road as the route is named and not an explicit controller/action.

@Html.RouteLink("Edit Customer", "CustomerEdit", new { IdCustomer = model.Id });

You can now make this in a different area or have another controller handle it later by changing your route defined and all your RouteLinks could remain the same.

Upvotes: 2

Related Questions