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

问题描述

给定多个HTML复选框:

 < input type =checkboxname =catIDsvalue =1 /> 
< input type =checkboxname =catIDsvalue =2/>
...
< input type =checkboxname =catIDsvalue =100/>

如何在操作中从FormCollection中获取整数数组:



public ActionResult Edit(FormCollection form)
{
int [] catIDs =(IEnumerable< int>)form [catIDs ]; // ???

//或者:
foreach(int [catIDs]的int catID为* SOME CAST *)
{
// ...
}

return View();
}






我阅读了相关问题,我不想更改我的操作参数,例如。 编辑(int [] catIDs)

解决方案

控件具有相同的名称,它们是逗号分隔的值。换句话说:

  string catIDs = form [catIDs]; 

catIDs是1,2,3,...



所以要获取所有的值你可以这样做:

  string [] AllStrings = form [ catIDs]。Split(','); 
foreach(AllStrings中的字符串项)
{
int value = int.Parse(item);
// handle value
}

或使用Linq:

  var allvalues = form [catIDs]。Split(',')Select(x => int.Parse(x)) ; 

然后您可以枚举所有的值。


Given multiple HTML checkboxes:

<input type="checkbox" name="catIDs" value="1" />
<input type="checkbox" name="catIDs" value="2" />
...
<input type="checkbox" name="catIDs" value="100" />

How do I retrive an array of integers from a FormCollection in an action:

public ActionResult Edit(FormCollection form)
{
    int [] catIDs = (IEnumerable<int>)form["catIDs"]; // ???

    // alternatively:
    foreach (int catID in form["catIDs"] as *SOME CAST*)
    {
        // ...
    }

    return View();
}


Note: I read the related questions and I don't want to change my action parameters, eg. Edit(int [] catIDs).

解决方案

When you have multiple controls with the same name, they are comma separated values. In other words:

string catIDs = form["catIDs"];

catIDs is "1,2,3,..."

So to get all the values you would do this:

string [] AllStrings = form["catIDs"].Split(',');
foreach(string item in AllStrings)
{
    int value = int.Parse(item);
    // handle value
}

Or using Linq:

var allvalues = form["catIDs"].Split(',').Select(x=>int.Parse(x));

Then you can enumerate through all the values.

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

09-22 12:22