Getting multiple checkboxes from FormCollection element
Asked Answered
M

2

15

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

Martial answered 11/4, 2010 at 16:34 Comment(1)
You should change the name value of the checkboxs into catIds[]Elinaelinor
D
20

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.

Dithyramb answered 11/4, 2010 at 16:48 Comment(1)
catIDs might be "1,false,3,4,false,6,...". you might have to remove those falses from your list.Falzetta
A
17

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.

Aggappora answered 5/7, 2012 at 15:31 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.