1

I have an array of checkboxes, and trying to filter them, but when no checkbox is checked, it throws an System.ArgumentNullException

public ActionResult UserEdit(string[] UsergroupIDs)
    {

      IEnumerable<Usergroup> userUsergroups = 
            UsergroupIDs.Where(x => x != "false")
                        .Select(x => (Usergroup)_ug.GetUsergroups(int.Parse(x)).FirstOrDefault());

How should I modify this one?

/M

1 Answer 1

2

Set the value to an empty list initially, then change it to the results of your query if the paremeters isn't null. Or, you could modify your view to include hidden fields for each checkbox that has the default (false) property so that parameter is never null. The latter is what the Checkbox helper method does so using it would also solve your problem. Even better, do both.

public ActionResult UserEdit(string[] UsergroupIDs)
{

  IEnumerable<Usergroup> userUsergroups = new List<UserGroup>();

  if (UsergroupIDs != null)
  {
       userUsergroups = UsergroupIDs.Where(x => x != "false")
                                    .Select(x => (Usergroup)_ug.GetUsergroups(int.Parse(x)).FirstOrDefault());
  }

  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

true, but it will fail if there are 8 checkboxes and all are false right? :)
No. In that case you get an empty collection. The null case is when no input values are passed back in the request. A checkbox is not submitted unless it is checked.

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.