Getting all selected checkboxes from a FormCollection
Asked Answered
P

3

7

I have a form which contains a whole bunch of checkboxes and some other types of control too. I need to retrieve the names of each selected checkbox.

What is the best way to do this? Can I do it with a linq query maybe?

So in pseudocode, I'm looking to do something like this:

var names = formCollection
               .Where(c => c is Checkbox && c.Checked)
               .Select(c => c.Name);

Update It seems the way MVC submits checkboxes is different from how a normal form would behave, as an hidden field is also rendered. I found the details here: How to handle checkboxes in ASP.NET MVC forms?

Anywho, I've got it working with the help of that thread and the answer from BuildStarted below. The following code did the trick.

var additionalItems = form.AllKeys
       .Where(k => form[k].Contains("true") && k.StartsWith("addItem"))
               .Select(k => k.Substring(7));
Pippas answered 30/9, 2010 at 14:33 Comment(2)
Thanks for that info. I normally just use the built in model binding and never really looked into detail what is output to the html with regards to checkboxes.Trickster
Nice example, I just updated code in my project for this.Lifesaver
T
5

Unfortunately that type of information isn't available in the collection. However if you prepend all your checkboxes with something like <input type='checkbox' name='checkbox_somevalue' /> then you can run a query like

var names = formCollection.AllKeys.Where(c => c.StartsWith("checkbox"));

Since only the checked values will be posted back you don't need to validate that they're checked.

Here's one that grabs only checked values

var names = formCollection.AllKeys.Where(c => c.StartsWith("test") && 
                        formCollection.GetValue(c) != null &&
                        formCollection.GetValue(c).AttemptedValue == "1");
Trickster answered 30/9, 2010 at 14:50 Comment(3)
I'm definitely getting ALL checkboxes posted back, not just the checked ones.Pippas
That's strange. A quick test reveals that isn't the case. Might be specific html causing that. but the <input type='checkbox' name='somename' /> form doesn't seem to work for me. However I've updated the answerTrickster
I've got it figured out now. Updated my question with a few more details. Thanks for your help :)Pippas
Q
0

This is one of the old questions not active for years but I stumbled on it. My problem was that I have an array of check boxes - let's say the name is 'IsValid' and wanted to get the status of each of the check boxes (my project was in MVC 5). On form submit i did the loop of form collection and got the values as...

if (key.Contains("IsValid"))
                    sV = (string[])collection.GetValue(key.ToString()).RawValue;

Since on form post the hidden field value was also posted with the checked check boxes; the array contained one additional value of 'false' for ONLY checked check box. To get rid of those i used following function; I hope that it helps somebody and if my approach is wrong then a better solution would be helpful to me as well!

sV = FixCheckBoxValue(sV);

        private string[] FixCheckBoxValue(string[] sV)
    {
        var iArrayList = new List<string>(sV);

        for (int i = 0; i < iArrayList.Count; i++)
        {
            if (iArrayList[i].ToString() == "true")
            {
                iArrayList.RemoveAt(i + 1);
            }                
        }
        return iArrayList.ToArray();
    }
Quiver answered 19/5, 2014 at 8:59 Comment(0)
L
0

Answering the post about the array of checkboxes, you could initially filter out the checkboxes by name.

var keys = formCollection.AllKeys.Where(x => x.StartsWith("IsValid");

Then you could just loop through them as a collection.

Lifesaver answered 26/12, 2021 at 18:12 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.