I have the following model:
public class MEUViewModel
{
public List<Obj1> Obj1s { get; set; }
public List<Obj2> Obj2s { get; set; }
public int IDMeu { get; set; }
public int IDMeu2 { get; set; }
public bool Chk1 { get; set; }
public bool Chk2 { get; set; }
public bool Chk3 { get; set; }
public bool Chk4 { get; set; }
}
My POST method is basic signing:
[HttpPost]
public ActionResult METODOPOST(MEUViewModel viewModel)
{
...
}
In my View I have the following Razor, one for each viewmodel bool:
@Html.CheckBoxFor(m => m.Chk1)
They are within BeginForm()
, I will not put the whole code because when doing submit
it falls into POST
normally.
It generates the following HTML:
<input data-val="true" data-val-required="O campo Chk1 é obrigatório." id="Chk1" name="Chk1" type="checkbox" value="true">
<input name="Chk1" type="hidden" value="false">
When doing POST all four bools come False, regardless of whether they are checked or not.
- The two properties that have an object list come with normal bind.
- IDs (ints) come with normal binds.
- If I put true in any of the four properties in the GET method it will generate the HTML with the checkbox checked.
TEMPORARY SOLUTION UPDATE
After trying many things: - I put the HTMl in the hand, according to the link that Marconi sent - I tried the JS do Paulo - I tried Warleson's answer.
And nothing works, thank you all.
What I did to function temporarily was to change the signature of the method:
[HttpPost]
public ActionResult METODOPOST(MEUViewModel viewModel, bool Chk1, bool Chk2, bool Chk3, bool Chk4)
{
And I play the value of the variables in the model. It's not beautiful, but that's what worked.
I'll leave the question open because I believe that a @Html.CheckBoxFor
in such a basic structure should work in a simpler way, who knows, somebody else answers some better solution.