1

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)
3
  • it's easier to use enum not bool? in your case othewise you should write custom ModelBinder. Commented Oct 29, 2015 at 11:06
  • Why not /employee/list/true and /employee/list/false? You cannot map "active" and "inactive" to a boolean property. Commented Oct 29, 2015 at 11:07
  • Well that's the current behaviour but it makes no sense to the user. True or false what? The enum is a good idea, I will investigate further. Thanks. Commented Oct 29, 2015 at 11:42

2 Answers 2

3

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)
{
    ...
}
Sign up to request clarification or add additional context in comments.

Comments

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'}")]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.