Alex Rivera | Logout

ASP.NET MVC: Route with optional parameter, but if supplied, must match \d+

Asked 2010-10-05T09:20:18.527
24

I'm trying to write a route with a nullable int in it. It should be possible to go to both /profile/ but also /profile/\d+.

routes.MapRoute("ProfileDetails", "profile/{userId}",
                new {controller = "Profile",
                     action = "Details",
                     userId = UrlParameter.Optional},
                new {userId = @"\d+"});

As you can see, I say that userId is optional but also that it should match the regular expression \d+. This does not work and I see why.

But how would I construct a route that matches just /profile/ but also /profile/ followed by a number?

Edit
Report

1 Answer

13

It's possible something changed since this question was answered but I was able to change this:

routes.MapPageRoute(
    null,
    "projects/{operation}/{id}",
    "~/Projects/ProjectWizard.aspx",
    true,
    new RouteValueDictionary(new
    {
        operation = "new",
        id = UrlParameter.Optional
    }),
    new RouteValueDictionary(new
    {
        id = new NullableExpressionConstraint(@"\d+")
    })
);

With this:

routes.MapPageRoute(
    null,
    "projects/{operation}/{id}",
    "~/Projects/ProjectWizard.aspx",
    true,
    new RouteValueDictionary(new
    {
        operation = "new",
        id = UrlParameter.Optional
    }),
    new RouteValueDictionary(new
    {
        id = @"\d*"
    })
);

Simply using the * instead of the + in the regular expression accomplished the same task. The route still fired if the parameter was not included, but if included it would only fire if the value was a valid integer. Otherwise it would fail.

answered 2012-05-07T22:49:55.680

Your Answer