2

I have a model

 public int Id { get; set; }
 public string Name { get; set; }
 public string Phone { get; set; }
 public bool IsChecked { get; set; }

I want to use checkboxfor in my view

 @Html.CheckBoxFor(model => model.IsChecked, new{@checked="checked"})

My checkbox is unchecked and view renders additional input

 <input name="IsChecked" type="hidden" value="false">

I don't understand how does it work? And how do i pass checkbox bool value to my model? Thanks.

2 Answers 2

3

If model.IsChecked is true when the control is rendered the checkbox will start as checked.

So just write:

@Html.CheckBoxFor(m => m.IsChecked)

The hidden field is generated always false by the helper method to make sure the propery name/value is submitted when the form posts even if the checkbox isnt cjecked by the user, because html forms only include checked checkboxes.

If the checkbox IS checked its property will take presedence over the hidden field because it comes before it.

1
  • It looks like it's not working like that anymore (at least not in the current version of Chrome)... I get always false even when I check the box. :(
    – Mischa
    Commented Feb 14, 2019 at 14:56
1

C#.NET MVC has some issues with CheckBoxFor() command. CheckBoxFor() autogenerates a hidden field with the same name & if it is not isolated in a [Div] by itself, it will sporadically drop checks going to the server. Even including a title or validation inside the [display-field] div can cause an issue with a CheckBoxFor(). Workarounds are to isolate CheckBoxFor() or add [onchange] update & it seems to work more consistently.

<div class="display-field">
    @Html.CheckBoxFor(m => Model.IsChecked, 
     new { onchange = "this.value = this.checked;"})
</div>

The server side should now catch true false into a bool model with the same name automatically.

public bool IsChecked { get; set; }

currently using MVC 4.x on VS 2017 PRO

Not the answer you're looking for? Browse other questions tagged or ask your own question.