ASP.NET MVC3 ValueProvider drops string input to a double property

Posted by Daniel Koverman on Stack Overflow See other posts from Stack Overflow or by Daniel Koverman
Published on 2012-10-22T22:34:55Z Indexed on 2012/10/22 23:00 UTC
Read the original article Hit count: 147

I'm attempting to validate the input of a text box which corresponds to a property of type double in my model. If the user inputs "foo" I want to know about it so I can display an error. However, the ValueProvider is dropping the value silently (no errors are added to the ModelState).

In a normal submission, I fill in "2" for the text box corresponding to myDouble and submit the form. Inspecting controllerContext.HttpContext.Request.Form shows that myDouble=2, among other correct inputs. bindingContext.ValueProvider.GetValue("myDouble") == 2, as expected. The bindingContext.ModelState.Count == 6 and bindingContext.ModelState["myDouble"].Errors.Count == 0. Everything is good and the model binds as expected.

Then I fill in "foo" for the text box corresponding to myDouble and submitted the form. Inspecting controllerContext.HttpContext.Request.Form shows that myDouble=foo, which is what I expected. However, bindingContext.ValueProvider.GetValue("myDouble") == null and bindingContext.ModelState.Count == 5 (The exact number isn't important, but it's one less than before). Looking at the ValueProvider, is as if myDouble was never submitted and the model binding occurs as if it wasn't. This makes it difficult to differentiate between a bad input and no input.

Is this the expected behavior of ValueProvider? Is there a way to get ValueProvider to report when conversion fails without implementing a custom ValueProvider? Thanks!

© Stack Overflow or respective owner

Related posts about asp.net-mvc-3

Related posts about model-binding