使用MVC属性路由将URL文本映射到布尔参数 [英] Map url text to boolean parameter with MVC attribute routing

查看:100
本文介绍了使用MVC属性路由将URL文本映射到布尔参数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

给出以下两个网址:

  • /员工/列表/活动
  • /员工/列表/无效

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

How do I map the active/inactive part of the url to a boolean action method parameter, active being true, inactive being false?

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

推荐答案

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

The enum is a correct approach as it allows you to easily add new statuses in the future :

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

public enum status { active, inactive }


即使基于单一责任原则,我还是希望这样一个更简单的解决方案:


Even though, based on the single responsibility principle, I would prefer a simpler solution like this:

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

这篇关于使用MVC属性路由将URL文本映射到布尔参数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆