简体   繁体   中英

Usage of checkboxfor & model in asp.net mvc c#

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.

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM