ASP.NET MVC2站点是否可以使用可选的枚举路由参数?如果是这样,如果没有提供,我们可以默认该值吗?

时间:2010-08-05 14:41:48

标签: .net asp.net-mvc asp.net-mvc-2 enums routes

我可以拥有像...这样的路线吗?

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

行动方法是......

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

如果此人未提供locationType的值,则默认为LocationType.Unknown

这可能吗?

更新#1

我已经删除了包含ONE方法的action方法(直到我开始工作)。它现在看起来像这样..

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

..我收到此错误消息......

  

参数字典包含一个   参数的无效输入   方法的'locationType'   “System.Web.Mvc.ActionResult   显示(MyProject.Core.LocationType)'   'MyProject.Controllers.GeoSpatialController'。   字典包含值   键入'System.Int32',但参数   需要值类型   'MyProject.Core.LocationType'。   参数名称:参数

是否认为可选路由参数LocationType是int32而不是自定义Enum

2 个答案:

答案 0 :(得分:6)

您可以提供如下默认值:

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


更新:

或者如果您使用的是.NET 3.5:

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


更新2:

public ActionResult Show(int? aaa, int? bbb, int locationType = 0) {
  var _locationType = (LocationType)locationType;
}

public enum LocationType {
    Unknown = 0,
    Something = 1
}

答案 1 :(得分:0)

您可以将DefaultValue属性添加到操作方法中:

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

或使用可选参数,具体取决于您使用的语言版本:

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