0

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.

tereško
  • 58,060
  • 25
  • 98
  • 150
Ian Davis
  • 19,091
  • 30
  • 85
  • 133
  • possible duplicate of [Proper usage of .net MVC Html.CheckBoxFor](http://stackoverflow.com/questions/12674572/proper-usage-of-net-mvc-html-checkboxfor) – Dominic Zukiewicz Mar 31 '14 at 20:10

1 Answers1

0

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

Community
  • 1
  • 1
Dominic Zukiewicz
  • 8,258
  • 8
  • 43
  • 61
  • But, checkboxes that _are_ checked are posted back, but with value as "on" and not "true". – Ian Davis Mar 31 '14 at 20:11
  • That's by design. They always post back with on, its part of the HTML specification. The ModelBinder knows this, so it converts the 'on' to true for you. – Dominic Zukiewicz Mar 31 '14 at 20:20