0

I am trying to get the following links:

  • / (maps to AccountController / Index)
  • /account/login (maps to AccountController / Login)
  • /2112/emails (maps to EmailsController / Index action and 2112 would be a route parameter)
  • /2112/emails/list (maps to EmailsController / List action and 212 would be a route parameter)

I am not being able to get the routes working as they seem to be conflicting with each other. The following makes me have the route param at all times which is not what I need. It will not bind without providing the database param.

routes.MapRoute(
    name: "Default",
    url: "{database}/{controller}/{action}",
    defaults: new { database = UrlParameter.Optional, controller = "Account", action = "Index" }
);
1
  • routes.MapRoute( name: "Default_with_hidden_index", url: "{controller}", defaults: new { action = "Index" }, constraints: new { action = "Index" } ); routes.MapRoute( name: "Default", url: "{controller}/{action}", defaults: new { controller = "Account", action = "Login" } ); This will solve the first and second topics I asked but not the other two. Commented Jul 24, 2015 at 11:36

1 Answer 1

1

Order is important in your route config. The key to routing in MVC is to start with the most specific routes and work up. Also as you have specific routing rules for the Emails controller, you can give the name of the controller specifically in the URL parameter. So here you would do this:

routes.MapRoute(
    name: "Emails",
    url: "{id}/Emails/{action}",
    defaults: new { controller = "Emails", action = "Index" },
    constraints: new { id = @"\d+" }
);

routes.MapRoute(
    name: "Default",
    url: "{controller}/{action}",
    defaults: new { controller = "Account", action = "Index" }
);
Sign up to request clarification or add additional context in comments.

3 Comments

He may also want an id in the default route, so I would think about adding a constraint for the id to be a number in the emails route
@DanielJ.G. It's possible, but we can't tell from the question text. I noticed a typo anyway so added it in while I was fixing that.
Thanks for the help. It works 100% for what I asked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.