0

I'd like to have an Index action for a "Users" controller that takes an optional parameter.

/Users/{id}

Or

/Users

I'd like to avoid:

/Users/Index/{id}

Or

/Users/Index/

I added a Route to map /Users/{id} to the Index action.

routes.MapRoute( "Users",
                 "Users/{id}",
                 new { controller = "Users", action = "Index", id =
                 UrlParameter.Optional});

That works fine. I ran into a problem when I added another action, "Add", also with an optional parameter, to the Users controller. The route I added earlier misinterprets Add as a parameter to the Index action. The "Index" action gets triggered for /Users/Add.

How can I get the best of both?

Thanks.

2 Answers 2

2

Set the constraints property to only allow numbers. That should fix your routing issue.

routes.MapRoute( "Users",
    "Users/{id}",
    new { controller = "Users", action = "Index", id = UrlParameter.Optional },
    new { id = "[0-9]+" }
);

Edit.

You can do it differently without using a regex constraint. Add the route Users/Add explicitly, adding it before the Index route:

routes.MapRoute( "Users",
    "Users/Add/{id}",
    new { controller = "Users", action = "Add", id = UrlParameter.Optional }
);
Sign up to request clarification or add additional context in comments.

2 Comments

@JoelSkrepnek indeed I do not. Please see my edit. You can always "hard wire" the routes like this; the key is to put the more specific ones first.
Thanks. I'll see how this goes over with the boss :).
0

You do no need to create routes for each action on your controller. A default route that is in global.asax at the beginning of creation of a project is enough for your needs:

routes.MapRoute(
    "Default", // Route name
    "{controller}/{action}/{id}", // URL with parameters
    new { controller = "Account", action = "Index", id = UrlParameter.Optional } // Parameter defaults
);

1 Comment

I created the route to avoid /Users/Index/{id}.

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.