tags:

views:

12

answers:

1

Hello

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

+2  A: 

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());
  }

  ...
}
tvanfosson
true, but it will fail if there are 8 checkboxes and all are false right? :)
molgan
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.
tvanfosson