views:

68

answers:

1

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: http://stackoverflow.com/questions/220020/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));
+1  A: 

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");
BuildStarted
I'm definitely getting ALL checkboxes posted back, not just the checked ones.
fearofawhackplanet
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 answer
BuildStarted
I've got it figured out now. Updated my question with a few more details. Thanks for your help :)
fearofawhackplanet