Getting all selected checkboxes from a FormCollection

前端 未结 2 1404
[愿得一人]
[愿得一人] 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 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");
    

提交回复
热议问题