Handling case-insensitive enum action method parameters in ASP.NET MVC

Skip to solution Using enums as action method parameters Say you have a enum, a sorting enum in this case. public enum SortType { NewestFirst, OldestFirst, HighestRated, MostReviews } ASP.NET will gladly let you use that enum as an action method parameter; you can even make it an optional parameter. To make it optional by routing, you need to make it nullable for the action method function parameter in your controller and add some guarding logic (!sort.HasValue or the like). routes.MapRoute( “DepartmentProducts”, “Department/Products/{sort}”, new { controller = “Department”, action = “Products”, sort = UrlParameter.Optional } ); public ActionResult Products(SortType? sort) { SortType requestedSort = sort ?? SortType.NewestFirst; … } To make the parameter optional by function parameter, just give the parameter a default value. routes.MapRoute( “DepartmentProducts”, “Department/Products/{sort}”, new { controller = “Department”, action = “Products” } ); public ActionResult Products(SortType sort = SortType.NewestFirst) { … } Both work just fine, though I lean toward the function parameter default. Regardless of implementation, you can call the method by a number of different URLs: https://www.somedomain.com/department/products/ (sort == null or SortType.NewestFirst, respectively) https://www.somedomain.com/department/products/OldestFirst/ https://www.somedomain.com/department/products/HighestRated/ https://www.somedomain.com/department/products/?sort=MostReviews Unfortunately, it requires the route value to be an exact match for the enum name, proper case included…. Continue reading