让所有选择复选框从的FormCollection [英] Getting all selected checkboxes from a FormCollection

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

问题描述

我有一个包含一大堆复选框和一些其他类型的控制过于形式。我需要检索每个选中的复选框的名称。

什么是做到这一点的最好方法是什么?我可以用LINQ查询,也许做呢?

因此​​,在伪code,我希望做这样的事情:

  VAR名=的FormCollection
               。凡(C => c是复选框和放大器;&安培; c.Checked)
               。选择(C => c.Name);

更新看来MVC提交复选框的方式是怎么样一个正常的形式会表现得有所不同,作为一个隐藏字段还呈现。我发现这里的细节:<一href=\"http://stackoverflow.com/questions/220020/how-to-handle-checkboxes-in-asp-net-mvc-forms\">http://stackoverflow.com/questions/220020/how-to-handle-checkboxes-in-asp-net-mvc-forms

Anywho,我知道了与线程的帮助,从下面BuildStarted答案工作。下面code做的伎俩。

  VAR additionalItems = form.AllKeys
       。凡(K =&GT;形式[K]。载(真)及与放大器; k.StartsWith(的addItem))
               。选择(K =&GT; k.Substring(7));


解决方案

不幸的是这种类型的信息是无法在集合中可用。然而,如果你prePEND所有的复选框的东西,如&LT;输入类型=复选框名称='checkbox_somevalue/&GT; ,那么你可以运行像<查询/ p>

  VAR名= formCollection.AllKeys.Where(C =&GT; c.StartsWith(复选框));

由于只有选中的值将被调回你不需要验证,他们正在检查。

这里有一个,抓住唯一选定值

  VAR名= formCollection.AllKeys.Where(C =&GT; c.StartsWith(测试)及和放大器;
                        formCollection.GetValue(C)= NULL和放大器;!&安培;
                        formCollection.GetValue(三).AttemptedValue ==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));

解决方案

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天全站免登陆