从 FormCollection 中获取所有选中的复选框 [英] Getting all selected checkboxes from a FormCollection

查看:31
本文介绍了从 FormCollection 中获取所有选中的复选框的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个表单,其中包含一大堆复选框和一些其他类型的控件.我需要检索每个选定复选框的名称.

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.

这样做的最佳方法是什么?我可以用 linq 查询来做吗?

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);

更新 MVC 提交复选框的方式似乎与普通表单的行为方式不同,因为还呈现了隐藏字段.我在这里找到了详细信息:如何处理 ASP.NET 中的复选框MVC 表单?

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?

任何人,我已经在该线程的帮助下以及下面来自 BuildStarted 的答案下开始工作了.下面的代码成功了.

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));

推荐答案

很遗憾,该类型的信息在集合中不可用.但是,如果您在所有复选框之前添加类似 <input type='checkbox' name='checkbox_somevalue'/> 的内容,那么您可以运行类似

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");

这篇关于从 FormCollection 中获取所有选中的复选框的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆