Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Razor checkbox not binding to Model

I'm an asp.net mvc newbie. I have a checkbox in my form

@Html.CheckBox("Don't show my number", Model.IsPhonePublic)

But whether I check the box or not the Model.IsPhonePublic is always false while submitting the form. Any pointers

like image 396
iJade Avatar asked Dec 02 '22 16:12

iJade


1 Answers

You are using the helper wrong, See definition here :

So you do this:

@Html.Label("Don't show my number") 
@Html.CheckBox("IsPhonePublic", Model.IsPhonePublic)

or

@Html.Label("Don't show my number") 
@Html.CheckBoxFor(m => m.IsPhonePublic)

or third and clean solution:

@Html.LabelFor(m => m.IsPhonePublic) 
@Html.CheckBoxFor(m => m.IsPhonePublic)

And in you model definition:

[DisplayName("Don't show my number")]
public bool IsPhonePublic { get; set; }
like image 134
Perfect28 Avatar answered Dec 11 '22 03:12

Perfect28