我能否循环遍历Collection.Request.Form?

9

我是一个有用的助手,可以为您进行文本翻译。

我有一些带有唯一标识符的复选框。是否可能在表单集合中查找所有复选框+uniquenum?

类似于以下内容 -

foreach (var item in Collection.Request.Form["checkbox" + with UniqueIDNum])
{
    //code
}
5个回答

41

不行。

相反,您可以循环遍历所有的键,并检查它们是否以 checkbox 开头。

例如:

foreach(string key in Request.Form) {
    if (!key.StartsWith("checkbox")) continue;
    ...
}

NameValueCollection枚举器返回的键是字符串。


不是我做的...这太完美了!谢谢! - MrM

4

或者类似于此类内容

var checkBoxes = Request.Form.Keys.Where(rs=>rs.StartsWith("dummy"));
foreach(string key in checkBoxes){
 // Your code
}

Request.Form.AllKeys - mxmissile

1
你应该能够使用Linq完成这个(这应该可以工作,但我没有测试): 我假设复选框的ID是“checkbox[ID]”。顺便说一句,在表单字段中重复使用ID非常糟糕。
var checkboxes = (from key in Request.Form.AllKeys where key = "checkbox" + UniqueIDNum)
foreach(string key in checkboxes)
{
     //do stuff
}

那是毫无必要的缓慢。AllKeys会复制一个数组。 - SLaks

1
        [AcceptVerbs(HttpVerbs.Post)]
        public ActionResult Index(FormCollection fc)
        {   
            string a = fc["hdn_1"].ToString(); // if you know for sure that it will have a value.
            string lbl_1 = null;

            foreach (var key in fc.AllKeys)
            {
                if (key.Contains("txt_1"))
                {
                    lbl_1 = fc["txt_1"].ToString();
                }
            }
         }

希望这能有所帮助。

0

我不得不在VB.NET中完成这个任务,虽然多年来没有使用过VB.NET,即使那时也没有使用过太多。我使用了Josh Wolf的答案来获得以下结果:

Dim checkedOrders As IEnumerable(Of String) = From key In Request.Form.AllKeys Where key.StartsWith("chk")

If checkedOrders.Count > 0 Then
   ' do stuff, loop through checkedOrders, etc
End If

请注意,我的所有复选框名称都以“chk”开头(例如“chk1038”,“chk1040”等)。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接