Reputation: 2273
I have a checkbox on my page, created as such:
@Html.CheckBoxFor(x => x.MyBoolValue)
Beneath that I have a WebGrid with sorting and paging, but on doing this I get a System.InvalidOperationException:
The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information.
The inner exception is:
{"true,false is not a valid value for Boolean."}
I know this is due to the binding of the CheckBox and the underlying Hidden value. On a page GET I deal with this using Contains("true") on the query string value, but how can I do this when the WebGrid is refreshed?
Upvotes: 3
Views: 3775
Reputation: 46
The problem is the name of your action parameter:
public ActionResult Product(ProductModel model);
For example the following will fix your issue:
public ActionResult Product(ProductModel request);
Upvotes: 0
Reputation: 76
If you want to maintain all standard validators or binders functionality and hidden field bother you someway. You can use this:
<input type="CheckBox"@(Model.BoolProperty ? " checked=\"checked\"" : string.Empty) name="BoolProperty" value="true"/>
Upvotes: 1
Reputation: 1115
I have found that removing the value from the ModelState resolves this, and doesn't seem to cause any side effects - perhaps someone could point out if I've missed anything?
In my controller I just add
ModelState.Remove("MyBoolValue");
Which means that
@Html.CheckBoxFor(x => x.MyBoolValue)
will fallback to using the Model value unless I'm mistaken?
Upvotes: 0
Reputation: 60516
MVC creates two inputs on @Html.CheckBoxFor(x => x.MyBoolValue)
. One Checkbox and one hidden field with the value false
.
He (MVC ;)) does this ensure that, even if you dont check the checkbox, the variable exists.
So if you check the box the variable value is true,false
and false
if not.
do this:
<input type="CheckBox" name="MyBoolValue" value="@Model.MyBoolValue"/>
or create a custom model binder that handles that.
ASP.NET MVC Custom Model Binding
Upvotes: 3