【问题标题】:Custom enum as optional parameter自定义枚举作为可选参数
【发布时间】:2013-04-09 06:22:39
【问题描述】:
  public enum Employee
    {
        FT,
        PT,
    }

这行不通

  public ActionResult Index(Employee s = Employee.PT)
        {
            ViewData["Message"] = s.ToString();

            return View("MyView");
        }

异常详细信息:System.ArgumentException:参数字典 包含方法的参数“s”的无效条目 'System.Web.Mvc.ActionResult 索引(SampleControllerEx.Controllers.Employee)' 在 'SampleControllerEx.Controllers.HomeController'。词典 包含“System.Int32”类型的值,但参数需要 “SampleControllerEx.Controllers.Employee”类型的值。范围 名称:参数

但以下一项有效,

public ActionResult Index([DefaultValue(Employee.PT)] Employee s)
        {
            ViewData["Message"] = s.ToString();

            return View("MyView");
        }

我可以知道为什么'DefaultValue'只支持自定义枚举,而可选参数(4.0)不支持它吗?

【问题讨论】:

  • 听起来你的路由错了。
  • @leppie DefaultValue 使用相同的路由。为什么 .net 4.0 选项不能正常工作?
  • 使参数可以为空会更容易。如果您要解决参数,您可以使用if ((s ?? Employee.PT) == Employee.PT) { // some code }

标签: c# asp.net .net asp.net-mvc


【解决方案1】:

你可以这样做:

 public ActionResult Index(int employeeType)
        {
            Employee s = (Employee) employeeType;
            ViewData["Message"] = s.ToString();

            return View("MyView");
        }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-22
    • 2013-01-29
    • 1970-01-01
    • 2012-03-27
    • 1970-01-01
    • 2011-05-30
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多