Razor checkbox not binding to Model

谁说我不能喝 提交于 2019-12-23 18:17:40

问题


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


回答1:


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; }



回答2:


 @Html.EditorFor(model => model.IsPhonePublic)
 @Html.Label('Don't Show my number.')


来源:https://stackoverflow.com/questions/24446828/razor-checkbox-not-binding-to-model

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!