Getting all selected checkboxes from a FormCollection

前端 未结 2 1370
[愿得一人]
[愿得一人] 2021-01-05 17:32

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 bes

相关标签:
2条回答
  • 2021-01-05 17:42

    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");
    
    0 讨论(0)
  • 2021-01-05 17:52

    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();
        }
    
    0 讨论(0)
提交回复
热议问题