@ Html.CheckBoxFor Works on GET, but not on POST

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 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.

    
asked by anonymous 22.07.2016 / 15:11

2 answers

1

Pass the value to the Controller

 @Html.CheckBoxFor(m => m.Chk1,new { Chk1  = true} )

By default it is already passed as false, so when it is checked it sends True

    
22.07.2016 / 15:46
0

Some alternatives

@Html.CheckBoxFor(m => m.Chk1,new { Chk1  = true} )

or

 @Html.CheckBoxFor(model => model.Chk1, htmlAttributes: new { Chk1 = true })

or

@Html.CheckBoxFor(m => m.Chk1,true)

Controlle

[HttpPost]
public ActionResult METODOPOST(MEUViewModel viewModel)
            {

CheckBox structure:

   public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, object htmlAttributes);


  public static MvcHtmlString CheckBoxFor<TModel>(this HtmlHelper<TModel> htmlHelper, Expression<Func<TModel, bool>> expression, IDictionary<string, object> htmlAttributes);
    
22.07.2016 / 16:41