Guilherme Longo
Guilherme Longo

Reputation: 57

Fetching Grouped Checkbox in a Controller

I have a checkbox group in a view.

name = "group";

I want to iterate throug this group of checkboxes but I need to find a way to fetch them together;

All selected checkboxes are being posted with their values.

Would I be able to do something like this (one straight statement):

string[] name = Request.QueryString('group');

foreach(string value in name) {
}

Upvotes: 1

Views: 128

Answers (2)

andleer
andleer

Reputation: 22568

The checkboxes are not returned on your query string but rather POSTed to your controller.

Only the selected checkbox values will be returned. To retrieve the entire list of possible checkbox values, you will need to reassemble those from your source.

@foreach (var item in Model.tags)
{
    <label>
        <input type="checkbox" name="Tag" value="@item.TagID"
        @if (item.Selected) { <text>checked="checked"</text> }
        />
        @item.Name
    </label>
}

[HttpPost]
public RedirectToRouteResult MyAction(IEnumerable<int> Tag)
{


}

Upvotes: 1

Dmitry Efimenko
Dmitry Efimenko

Reputation: 11203

andleer's solution will work (with a minor adjustment that I made to his answer and that needs to be approved). However, there is a better way to handle list of checkboxes. Please see CheckBoxList(For) extension

Upvotes: 0

Related Questions