0

I have a view in MVC3, that has bunch of check boxes. The user checks one or more check boxes and clicks on submit. On submit, I would like to display the checked boxes values in a partial view or a view.

<table>
   <tr><td> @Html.Label("Label1")</td><td>  @Html.CheckBox("CB1")</td></tr>   
   <tr><td> @Html.Label("Label2")</td><td>  @Html.CheckBox("CB2")</td></tr>
   <tr><td> @Html.Label("Label3")</td><td>  @Html.CheckBox("CB3")</td></tr>
</table>
 @Html.ActionLink("Submit", "SubmitCB")

Controller action:

 public ActionResult SubmitCB()
    {
      @foreach (var checked in ?) 
        {
             //Display checked only here...            
        }
    }

I was wondering how I can loop through and display the results in a partial view or a view. Thanks for your help.

ZVenue
  • 4,967
  • 16
  • 61
  • 92

1 Answers1

1

You need to change your action to allow it to bind to the submitted form. Also, you need to submit the form properly (I would suggest wrapping it in a form tag and using a submit button as opposed to an action link. But here's what your action would look like:

public ActionResult SubmitCB(bool CB1, bool CB2, bool CB3)
{
    ... // use CB1, CB2, and CB3 here
}

If you'd like these checkboxes to be in a list, you need to give them all the same name and different values. Then You can have your action take in something like SubmitCB(string[] CBs) and look at the values in that array (they'll be the values of the selected checkboxes).

Milimetric
  • 13,411
  • 4
  • 44
  • 56
  • If I have a lot more check boxes than 3, how do I handle this.. cumbersome to have so many checkboxes as parameters? – ZVenue Jul 18 '11 at 15:02
  • Use the second method. All your checkboxes should have the same name and different Ids. I usually choose to not use the Html.CheckBox helper for this as it's kind of dumb about it. But that's your choice. Just check SO for MVC 3 checkbox list: http://stackoverflow.com/questions/2067786/asp-net-mvc-checkbox-group – Milimetric Jul 18 '11 at 15:22