Reputation: 423
I'm trying to so a simple form to send some data. My form have a list of checkboxes and next to each box, a name and a role of person. What I want to do : recover the list of person that box have been checked. I've created a model that way to do that :
public class CoupleModel
{
public Boolean isSelected { get; set; }
public String name {get; set;}
public String login { get; set; }
public String role { get; set; }
public CoupleModel(String name, String login, String role)
{
this.name = name;
this.login = login;
this.role = role;
this.isSelected = false;
}
public CoupleModel()
{
this.isSelected = false;
}
}
My form looks like this :
@using (Html.BeginForm("CreateInventory", "Home"))
{
@Html.Action("PersonListInventory")
<button type="submit" class="btn btn-primary">Validate creation</button>
}
And the PartialView linked to it is this one :
@model List<MyApp.Models.CoupleModel>
<table class="table table-striped table-bordered"">
<tbody>
@for (int i = 0; i < Model.Count(); i++) {
<tr>
<td>
@Html.EditorFor(m => m[i].isSelected)
</td>
<td>
@Html.EditorFor(m => m[i].name)
</td>
<td>
@Html.EditorFor(m => m[i].role)
</td>
</tr>
}
</tbody>
</table>
And then, in my controller view, I just want to list the name of the people where the box have been checked :
[HttpPost]
public ActionResult CreateInventory(List<CoupleModel> model)
{
String res = "";
foreach (var item in model) {
if (item.isSelected)
{
res += "selected : " + item.login + "<br>";
}
else
{
res += item.login + "<br>";
}
}
ViewBag.Res = res;
return View();
}
But only the "isSelected" part is set, that's to say that login is always blank when displaying. Why isn't it set ? Do I need to do some particular binding ?
Upvotes: 0
Views: 1231
Reputation: 1038930
that's to say that login is always blank when displaying.
That's perfectly normal. You don't have a corresponding field in your form. You need to add it as a hidden field:
@Html.HiddenFor(m => m[i].login)
Upvotes: 2
Reputation: 3591
You need to add @Html.HiddenFor(..)
s for the fields you want to pass along.
The result:
@for (int i = 0; i < Model.Count(); i++) {
@Html.HiddenFor(m => m[i].login)
<tr>
<td>
@Html.EditorFor(m => m[i].isSelected)
</td>
<td>
@Html.EditorFor(m => m[i].name)
</td>
<td>
@Html.EditorFor(m => m[i].role)
</td>
</tr>
}
On the side, please use the .NET naming convention.
Upvotes: 1