1

I'd like to return a list of Personnes from checked checkbox in my view and get it in my controller but selectedObjects count is always 0...

Here's my view with checkboxes:

@using (Html.BeginForm("Presence", "Evenement"))
{
    foreach (var p in Model.Personnes)
    {
        <input type="checkbox" name="selectedObjects" value="@p" />
    }
    @Html.AntiForgeryToken()
    <input type="submit" value="Valider Presence" class="btn btn-primary" />
}

my controller:

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Presence(List<Personne> selectedObjects)
{
    return View(selectedObjects);
}
tereško
  • 58,060
  • 25
  • 98
  • 150
Xr4y
  • 29
  • 8
  • Possible duplicate of [CheckboxList in MVC3 View and get the checked items passed to the controller](http://stackoverflow.com/questions/5284395/checkboxlist-in-mvc3-view-and-get-the-checked-items-passed-to-the-controller) – Ondrej Svejdar Oct 27 '15 at 08:33
  • 2
    You cannot bind a checkbox to a complex object (look at the html your generating!). You need to set the `value` attribute to a property of your model e.g. `value="@p.ID"` and the method needs to be `Presence(int[] selectedObjects)` –  Oct 27 '15 at 08:40
  • Thanks I manage to get the [] of Id's, now I've to find each person in db who matches the id – Xr4y Oct 27 '15 at 09:05

1 Answers1

0

You cannot bind a checkbox to complex object. A checkbox only posts back a single value. Instead you need to bind to a property of Personne, for example, if it has a property int ID, then

foreach (var p in Model.Personnes)
{
    <input type="checkbox" name="selectedObjects" value="@p.ID" />
}

and then change the POST method signature to

public ActionResult Presence(int[] selectedObjects)