Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can an ASP.NET MVC2 site have an optional enum route parameter? If so, can we default that value if not provided?

can I have a route like...

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

Where the action method is...

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

and if the person doesn't provide a value for locationType .. then it defaults to LocationType.Unknown.

Is this possible?

Update #1

I've stripped back the action method to contain ONE method (just until I get this working). It now looks like this ..

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

.. and I get this error message...

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

Is it thinking that the optional route parameter LocationType is an int32 and not a custom Enum ?

like image 761
Pure.Krome Avatar asked Aug 05 '10 14:08

Pure.Krome


1 Answers

You can supply a default value like so:

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
}
like image 150
Fabian Avatar answered Sep 30 '22 12:09

Fabian