Reputation: 23
Here's the situation, i have a ClassA which contains a list of ClassB objects. ClassB has 3 variables, an int, a bool, and a string. I'm trying to change the bool variable when i list it ( using foreach inside a View). The listing part runs smoothly(i get to choose which checkbox to check), but values of checkboxes that user selects dont get remembered.
This is a view model :
@model ClassA
...
@using (Html.BeginForm("Upload", "Registration", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
...
<p>Your name: @Html.TextBoxFor(x => x.FirstName) </p>
<p>Adress: @Html.TextBoxFor(x => x.Adress)</p>
foreach (ClassB check in Model.ClassBlist)
{
<p>@check.Name:@Html.CheckBoxFor(x=>check.attributeChecked,check.itemID)</p>
}
``...
}
Upvotes: 2
Views: 935
Reputation: 1038840
Try like this:
for (var i = 0; i < Model.ClassBlist.Count; i++)
{
<p>
@Html.DisplayFor(x => x.ClassBlist[i].Name)
:
@Html.CheckBoxFor(
x => x.ClassBlist[i].attributeChecked,
Model.ClassBlist[i].itemID
)
</p>
}
This time the CheckBoxFor helper will generate correct name for the corresponding input field so that the default model binder is able to properly bind it when you submit the form.
Upvotes: 2