开发者

Getting multiple checkboxes from FormCollection element

开发者 https://www.devze.com 2022-12-26 16:54 出处:网络
Given multiple HTML checkboxes: <input type=\"checkbox\" name=\"catIDs\" value=\"1\" /> <input type=\"checkbox\" name=\"catIDs\" value=\"2\" />

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(FormCollectio开发者_Go百科n 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.


The safer way would be to use: form.GetValues("CatIds") this will get you the array passed in the post. Just in case you had commas in your input.

0

精彩评论

暂无评论...
验证码 换一张
取 消