lundi 3 septembre 2018

MVC CheckBoxFor added hidden input problem

I have this attribute in my Model:

public bool Publish { get; set; }

And I want to be able to edit it in a view specifically using razor. So I used CheckBoxFor as so...

@Html.CheckBoxFor(model => model.Publish)

And razor generates this code:

<input data-val="true" data-val-required="Required field." id="Publish" name="Publish" type="checkbox" value="true">
<input name="Publish" type="hidden" value="false">

I understand the hidden input with value false is needed for when you don't check the box, so that it always has a value when reaching the controller action, however the value always arrives as false no matter if I check the box or not.

When I write the html myself, without including the hidden input, it works like a charm, but I want to use Razor, as it seems cleaner than displaying checked checkbox or unchecked using an if for when there's already data to edit.

All other attributes used from my model reach the controller with correct values.




Aucun commentaire:

Enregistrer un commentaire