【问题标题】:Map url text to boolean parameter with MVC attribute routing使用 MVC 属性路由将 url 文本映射到布尔参数
【发布时间】:2015-10-29 11:01:14
【问题描述】:

给定以下两个网址:

  • /employee/list/active
  • /employee/list/inactive

如何将 url 的活动/非活动部分映射到布尔操作方法参数,活动为真,非活动为假?

[Route("employee/list")]    
public ActionResult List(bool? active = null)

【问题讨论】:

  • 在您的情况下使用enum 而不是bool? 更容易,否则您应该编写自定义ModelBinder
  • 为什么不/employee/list/true/employee/list/false?您不能将“活动”和“非活动”映射到布尔属性。
  • 嗯,这是当前的行为,但对用户来说没有意义。真假什么的?枚举是个好主意,我会进一步调查。谢谢。

标签: asp.net-mvc asp.net-mvc-routing attributerouting


【解决方案1】:

枚举是一种正确的方法,因为它允许您在将来轻松添加新状态:

[Route("employee/list/{status}")]
public ActionResult List(status status)
{
    ...
}

public enum status { active, inactive }


即使,基于单一责任原则,我更喜欢这样一个更简单的解决方案:
[Route("employee/list/active")]
public ActionResult ListActive()
{
    return List(true);
}

[Route("employee/list/inactive")]
public ActionResult ListInactive()
{
    return List(false);
}

public ActionResult List(status status)
{
    ...
}

【讨论】:

    【解决方案2】:

    我对其进行了修改以使用字符串,因此它的工作方式如下:

    [Route("employee/list")]
    [Route("employee/list/{active}")]
    public ActionResult List(string active ="both")
    {
       ///Stuff happens here
    }
    

    如果您需要参数是可选的,添加第一个无参数路由很重要。

    更新:这条路线也可以使用

    [Route("employee/list/{active='both'}")]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2019-03-29
      • 2012-06-16
      • 1970-01-01
      • 2013-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-03-25
      相关资源
      最近更新 更多