Alexander Schimpf
Alexander Schimpf

Reputation: 2392

How do I get the selected values of a checkbox list?

If I have a CheckBoxList within a form, like this...

@using (Html.BeginForm("Save", "Product", FormMethod.Post))
{
    ...

    @Html.CheckBoxList("Categories", Model.AllCategories);

    ...
}

... how can I get a list of selected values (checked values) in my controller action?

For example, if the check box list has items with values of:

Cat. 1

Cat. 2

Cat. 3

Cat. 4

...and Cat. 2 and Cat. 3 are selected, how can I get an array containing those values?

Upvotes: 0

Views: 1366

Answers (2)

Alexander Schimpf
Alexander Schimpf

Reputation: 2392

In the simplest case, the controller action should look like this (in the Product controller):

[HttpPost]
public ActionResult Save(string[] Categories)
{
    // Process selected checkbox values here, using the Categories array
    ...
}

In a more complex case (with more form fields), it may be better to use a view model, and add a Categories property to it.

public class MyViewModel
{
    ...

    public string[] Categories { get; set; }

    ...
}

Controller action:

[HttpPost]
public ActionResult Save(MyViewModel model)
{
    // Process selected checkbox values here, using the model.Categories array
    ...
}

Simple Q & A, but hopefully it will help someone looking for the answer (like I was, when I first started learning ASP.NET MVC).

P.S. If you've got something better or more detailed, please post it.

Upvotes: 1

twaldron
twaldron

Reputation: 2752

Check out the answer for this question Here I use this all the time and it works perfectly.

Upvotes: 0

Related Questions