2
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 signature:
[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 inside a BeginForm()
, I’m not going to put all the code because by doing the submit
he falls in the 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 the POST all four bools come False, regardless of whether they are marked or not.
- The two properties that have a list of objects comes with the normal bind.
- Ids (ints) come with normal Ids.
- If I put true in any of the four properties in the GET method it will generate HTML with checkbox marked.
UPDATE WITH TEMPORARY SOLUTION
After trying many things: - I put the HTML in my hand, according to the link Marconi sent - I tried Paul’s JS - I tried Warleson’s reply
and nothing working, thank you all.
What I did to work temporarily was 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 variables in the model. It’s not pretty, but it worked.
I’ll leave the question open because I believe that a @Html.CheckBoxFor
in such a basic structure should work more simply, perhaps someone will answer some better solution.
Look at this question she looks a lot like.
– Marconi
Guess what’s happening is : Going the value of the Hidden input
– PauloHDSousa
@Html.Editorfor(x => x.Chk1) Already tried this?
– PauloHDSousa
I’ve also tried @Paulohdsousa . Same result.
– Ricardo
Before giving Submit, do this if ($('[name="Chk1"]:checked'). length > 0) $('[name="Chk1"]:Hidden'). val(true);
– PauloHDSousa
I did the JS, I sent an Alert to see if the value was changed, it was changed, but the controller is missing. @Paulohdsousa
– Ricardo