Retrieving All Selected Checkboxes from FormCollection

I have a form that contains a whole bunch of checkboxes and some other types of controls. I need to get the names of each selected checkbox.

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

So, in the pseudocode, I want to do something like this:

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

Refresh MVC seems to present checkboxes different from how the normal form will behave, since a hidden field is also displayed. I found the details here: How to handle checkboxes in ASP.NET MVC forms?

Anywho, it works for me using this 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)); 
+6
checkbox asp.net-mvc controls webforms formcollection
source share
2 answers

Unfortunately, this type of information is not available in the collection. However, if you add all of 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 verified values ​​will be sent back, you do not need to verify that they are checked.

Here is one that captures only verified values

 var names = formCollection.AllKeys.Where(c => c.StartsWith("test") && formCollection.GetValue(c) != null && formCollection.GetValue(c).AttemptedValue == "1"); 
+5
source share

This is one of the old questions, not valid for many years, but I came across it. My problem was that I have a set of flags - let the name "IsValid" want to get the status of each of the flags (my project was in MVC 5). In the submit form, I looped through the collection of forms and got the values ​​as ...

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

Since on the post form, the value of the hidden field was also sent with the flags checked; another false flag value was added to the array for ONLY. To get rid of them, I used the following function; I hope this helps someone, and if my approach is wrong, then the best solution will be useful to me too!

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

All Articles