Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

asp.net mvc checkbox inconsistency

I'm using an checkbox on an ASP.NET MVC form like so:

<%=Html.CheckBox("AgreeToRules", Model.AgreeToRules)%>

The AgreeToRules property on the model is a boolean value. During testing, this all worked fine. However, now that we've gone live with this app, I'm seeing a relatively small but significant number of errors with the following messaging:

System.Web.HttpUnhandledException: Exception of type 'System.Web.HttpUnhandledException' was thrown. ---> System.InvalidOperationException: The parameter conversion from type 'System.String' to type 'System.Boolean' failed. See the inner exception for more information. ---> System.FormatException: Y is not a valid value for Boolean. ---> System.FormatException: String was not recognized as a valid Boolean.

This appears to happen when the view engine tries to render the form after a post, and the value of the checkbox that is returned from the ValueProvider looks like:

Y,false

OR

N,false

The html that is rendered in the original form looks like:

<input id="AgreeToRules" name="AgreeToRules" type="checkbox" value="true" />
<input name="AgreeToRules" type="hidden" value="false" />

During testing, I expected (and showed) the posted value to look like:

true,false

if checked or

false

if not checked. So where is the N and Y coming from?

I added user agent to the list of information returned from the error handler and it appears (so far) that all of the errors are occuring under windows XP with FF 3.0.10, but that's exactly what I have tested with and the problem did not exist during testing.

Any thoughts?

like image 880
Chris Avatar asked Jun 01 '09 19:06

Chris


2 Answers

We had this same issue on a project I'm working on (MVC 2). We solved it by replacing the helper with plain html code:

Before: <%= Html.CheckBox("Credit", false, new {@validate = "required"}) %>

After:

<input type="checkbox" name="Credit" value="true" validate="required" />
<input type="hidden" name="Credit" value="false" />
like image 122
Daniel Avatar answered Oct 11 '22 09:10

Daniel


It's quite possible that your site is being hit by spambots that are submitting this value, and not real users. The more sites I add automated logging and emailing to, the more of these types of "probes" and errors (though not exactly the type you mention, with a "Y" for a checkbox) that I see piling into my inbox. Does your logging also capture the rest of the submitted form contents?

like image 26
Funka Avatar answered Oct 11 '22 08:10

Funka