Map url text to boolean parameter with MVC attribute routing

依然范特西╮ 提交于 2019-12-10 11:52:16

问题


Given the following two urls:

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

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)

回答1:


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



回答2:


I reworked it to use a string so it worked like this:

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

It's important to add the first, parameterless route if you need the parameter to be optional.

Update: This route works too

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


来源:https://stackoverflow.com/questions/33412425/map-url-text-to-boolean-parameter-with-mvc-attribute-routing

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!