简体   繁体   中英

Bool from viewmodel is not binding in MVC action on a post

I have a view model that has TestStr and TestBool as properties. If I submit the form, only the TestStr value is getting set to the bound view model, but not the TestBool . The value in the form collection for TestBool is set to "on" , is that the issue? Should it be set as true for it to be marked as true?

My c# view model:

public class MyViewModel { 
  public bool TestStr { get; set; }
  public bool TestBool { get; set; }
}

My razor view, inside the form:

<input name="TestStr" value="this is getting set in my MVC action" />
<input name="TestBool" checked=checked /> // this always gets set to false, even tho it's checked

My MVC action:

public ActionResult(MyViewModel vm) {
  // vm.TestBool is always false
}

I notice that if I use the @Html.CheckBoxFor(...) it does correctly bind it in my MVC action. Is it possible to do this using the typed-out html? Only because I have some collections I'm working with, so I'm having to provide the input names for each.

Its because checkboxes don't post back if they are not checked. The HTML helper actually adds a hidden field for the unchecked version, then resolves the conflict (checked / not checked ) correctly.

If you want to preserve other fields, but don't want to display them, Html.HiddenFor can be used to preserve the values.

This post shows someone with the same issue

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