0

When I have the following form:

<input type="checkbox" name="modules" value="1" />
<input type="checkbox" name="modules" value="2" />
<input type="checkbox" name="modules" value="3" />

This wil correctly send to the following MVC controller:

[HttpPost]
public ActionResult Submit(string[] modules)
{

}

But what when the above form is wrapped into an for-loop, like this:

@for (int i = 0; i < cart.Events.Count; i++)
{
    <h1>@cart.Events[i].Name</h1>
    <input type="checkbox" name="modules" value="1" />
    <input type="checkbox" name="modules" value="2" />
    <input type="checkbox" name="modules" value="3" />
}

With a controller that looks something like this:

[HttpPost]
public ActionResult Submit(TestObject modules)
{

}

public class TestObject
{
    public string[] modules { get; set; }
}

That will not work correctly, because MVC doesn't know how to bind the form data to the object. I want to send the selected values only, because it's not said that the count of module checkboxes is always the same.

How to fix this?

Rahul Singh
  • 21,585
  • 6
  • 41
  • 56
Corné Strijkert
  • 290
  • 1
  • 5
  • 12
  • Your model needs a property say `bool IsSelected` and a property for the value, say `int Value` - refer [this answer](http://stackoverflow.com/questions/29542107/pass-list-of-checkboxes-into-view-and-pull-out-ienumerable/29554416#29554416) for an example –  Feb 23 '17 at 09:11
  • can you also add code of TestObject – Usman Feb 23 '17 at 09:18

1 Answers1

0

All the checkbox have the same names, you could customize the name by : @("modules" + cart.Events[i].Name).