Jessy Houle
Jessy Houle

Reputation: 1921

MVC Route Constraint for bool

What would be a valid regex for a MVC route constraint passing a bool? For example, I have the below route:

routes.MapRoute("MenuRouteWithExtension",
    "Menu.mvc/{action}/{projectId}/{dealerId}/{isGroup}",
     new { controller = "Menu", action = "RedirectUrl",
           projectId = "", dealerId = "", isGroup = "" }
     new { projectId = @"\d+", dealerId = @"\d+", isGroup = @"???" });

Basically, I need to know what would be valid in place of the ??? in the above code example.

This way, the Action on the other end can use the bool type like:

public ActionResult RedirectUrl(int projectId, int dealerId, bool isGroup)

Thank you in advance for your input.

Upvotes: 6

Views: 3470

Answers (1)

Dan Atkinson
Dan Atkinson

Reputation: 11728

isGroup = @"^(true|false)$"

So...

routes.MapRoute(
  "MenuRouteWithExtension",
  "Menu.mvc/{action}/{projectId}/{dealerId}/{isGroup}",
  new
  {
    controller = "Menu",
    action = "RedirectUrl",
    projectId = "",
    dealerId = "",
    isGroup = "" //Possibly set this to 'true' or 'false'?
  },
  new
  {
    projectId = @"^\d+$",
    dealerId = @"^\d+$",
    isGroup = "^(true|false)$"
  }
);

Casing shouldn't matter, so True should be accepted, as well as falSE.

Also, I've put ^ and $ on the regex values so that they won't match, for instance blahtrueblah.

Upvotes: 17

Related Questions