问题
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