Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 293
Jessy Houle Avatar asked Jan 13 '10 18:01

Jessy Houle


People also ask

Can we add constraints to the route in MVC?

Attribute Routing is introduced in MVC 5.0. We can also define parameter constraints by placing a constraint name after the parameter name separated by a colon. There are many builtin routing constraints available. We can also create custom routing constraints.

How do you add a constraint to a route?

Creating Route Constraint to a Set of Specific Values routes. MapRoute( "Default", // Route name "{controller}/{action}/{id}", // Route Pattern new { controller = "Home", action = "Index", id = UrlParameter. Optional }, // Default values for parameters new { controller = "^H.

Can we define multiple route constraints for a route parameter?

We can apply the multiple constraints to a parameter by a colon (:) separator. [Route(URLPath/{parameterName: constrain:Constrain:….})] In the preceding example, the route will only be selected if the parameter id is an integer as well as a value of id greater than 1000.


1 Answers

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.

like image 109
Dan Atkinson Avatar answered Sep 20 '22 05:09

Dan Atkinson