Can an ASP.NET MVC2 site have an optional enumeration route parameter? If so, can we use this value by default if it is not specified?

Can I have a route like ...

routes.MapRoute( "Boundaries-Show", "Boundaries", new { controller = "Boundaries", action = "Show", locationType = UrlParameter.Optional }); 

Where is the method of action ...

 [HttpGet] public ActionResult Show(int? aaa, int? bbb, LocationType locationType) { ... } 

and if the person does not provide a value for locationType .., then by default it is equal to LocationType.Unknown .

Is it possible?

Update # 1

I canceled the action method to contain ONE method (only until I get this working). Now it looks like this.

 [HttpGet] public ActionResult Show(LocationType locationType = LocationType.Unknown) { .. } 

.. and I get this error message ...

The parameter dictionary contains an invalid entry for the 'locationType' parameter for the 'System.Web.Mvc.ActionResult Show (MyProject.Core.LocationType)' method in 'MyProject.Controllers.GeoSpatialController. The dictionary contains a value of type' System.Int32 ', but the parameter requires values โ€‹โ€‹of type 'MyProject.Core.LocationType. Parameter name: parameters

Does the optional locationType route parameter think it is int32, not a custom Enum ?

+7
enums asp.net-mvc asp.net-mvc-2 routes
source share
2 answers

You can specify a default value:

 public ActionResult Show(int? aaa, int? bbb, LocationType locationType = LocationType.Unknown) { ... } 


UPDATE:

Or if you are using .NET 3.5:

 public ActionResult Show(int? aaa, int? bbb, [DefaultValue(LocationType.Unknown)] LocationType locationType) { ... } 


UPDATE 2:

 public ActionResult Show(int? aaa, int? bbb, int locationType = 0) { var _locationType = (LocationType)locationType; } public enum LocationType { Unknown = 0, Something = 1 } 
+6
source share

You can add the DefaultValue attribute to your action method:

 [HttpGet] public ActionResult Show(int? aaa, int? bbb, [DefaultValue(LocationType.Unknown)]LocationType locationType) { ... } 

or use additional parameters depending on the version of the language you are using:

 [HttpGet] public ActionResult Show(int? aaa, int? bbb, LocationType locationType = LocationType.Default) { ... } 
0
source share

All Articles