开发者

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 ?


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
}


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) { ... }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜