Search code examples
c#asp.net-mvcasp.net-mvc-3model-view-controllerasp.net-mvc-routing

using mvc route constraints so a url can only be mapped to one of three possible params


Here is my route:

routes.MapRoute(null, "myaccount/monitor/{category}", // Matches
                new { controller = "MyAccount", action = "Monitor", category = (string)null }
);

I would like to add a constraint so the category can only match a null or one of three params (i.e. overview, projection, history)


Solution

  • You can use UrlParameter.Optional to allow nulls, and also use the constraints parameter of the MapRoute method..

     routes.MapRoute(null,
                          "myaccount/monitor/{category}", // Matches
                          new { controller = "MyAccount", action = "Monitor", category = UrlParameter.Optional  },
                          new { category = "overview|projection|history"}
                );