Reputation: 1007
My models
public class User
{
public string Id { get; set; }
[Display(Name = "")]
public bool IsSelected { get; set; }
[Display(Name = "Nom")]
public string Name { get; set; }
[Display(Name = "Prénom")]
public string Firstname { get; set; }
}
public class ListUser
{
public string ClickedButton { get; set; }
[Display(Name = "")]
public List<Models.User> Users;
}
index.cshtml
On this page I display all the users from ListUser
, each user is selectable with a checkbox
@model Models.ListUser
<!-- some content here -->
<script>
function clickedButton(i){
document.getElementById("ClickedButton").value = i;
return true;
}
</script>
@using (Html.BeginForm("Index", "Users", new { ReturnUrl = ViewBag.ReturnUrl }, FormMethod.Post, new { @class = "form-horizontal", role = "form" }))
{
@Html.ValidationSummary(true, "", new { @class = "text-danger" })
@Html.HiddenFor(m => m.ClickedButton);
for (var i = 0; i < Model.Users.Count(); i++)
{
@Html.CheckBoxFor(m => m.Users[i].IsSelected)
@Html.DisplayNameFor(m => m.Users[i].Name)
@Html.DisplayFor(m => m.Users[i].Name)
@Html.DisplayNameFor(m => m.Users[i].Firstname)
@Html.DisplayFor(m => m.Users[i].Firstname)
}
<input type="submit" value="Réinitialiser les mots de passe" class="btn btn-default" onclick="clickedButton('psw')"/>
}
And here's the controller (this controller is called when I submit the form)
[HttpPost]
public ActionResult Index(ListUser model)
{
// I added a breakpoint here
return this.RedirectToAction("Index", "Home");
}
I want to send all the selected users to the controller, for instance when I select 4 users, I want to retrieve them in the controller :
The problem : When I submit the form only the ClickedButton
field is set in the model, the users I selected (via checkboxes) are not set.
What is the problem?
Upvotes: 1
Views: 1117
Reputation:
Users
is a field in your ListUser
class, not a property, and the DefaultModelBinder
does not bind fields. Change it to
public class ListUser
{
public string ClickedButton { get; set; }
[Display(Name = "")]
public List<Models.User> Users { get; set; } // change
}
Note also that the only property that will be bound is the IsSelected
property of User
, and you will want to include a hidden input in the view for the Id
property so that you an match up the correct selections
@Html.HiddenFor(m => m.Users[i].Id)
Upvotes: 1
Reputation: 2747
Small change can help and be sure about all inputs have proper names in html form
public ActionResult Index(string ClickedButton, User model)
Upvotes: 0