views:

109

answers:

2

Hi folks,

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 ?

+1  A: 

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
}
Fabian
For .NET 4.0. MVC 2 is also available in 3.5.
Yuriy Faktorovich
@Yuriy, updated my answer.
Fabian
Which way is more a 'standard' ?
Pure.Krome
@Pure.Krome The new way (4.0) is more readable and thus prefered imho.
Fabian
@Fabian - do i still need to define the parameter as optional in my global.asax route registration? what about the 2 nullable ints? mark them as optional in the route registration also?
Pure.Krome
@Pure.Krome yes you still need to define it as optional, because the parameter wont be present but the route still has to match. You can define those 2 optional and give them a default value aswell if you require this.
Fabian
@Fabian - I've updated the opening post with an update / error message.
Pure.Krome
Intresting, it is most likely serializing that to an int. I guess the only way of doing it by casting, updating my answer.
Fabian
A: 

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 optional parameters depending on what language version your using:

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