Question

I have a fairly complex ViewModel containing decimal properties, which are exposed to the user in the form of text boxes. I want a textbox with no value to be interpreted as zero. (The properties in the underlying domain object are non-nullable, and the default value is 0.)

When the DefaultModelBinder binds the view data to the ViewModel, decimal properties with blank strings for inputs are initialized to zero (as is standard in .NET), but the DefaultModelBinder is adding errors to the ModelState for the blank text boxes. As a result the ModelState is invalid and the user sees a whole bunch of "A value is required." errors for the textboxes they left blank.

How can I stop these errors from being added to the ModelState?

Was it helpful?

Solution

The best thing that you could do in this situation is to create a ViewModel. Instead of binding directly to your Domain Model, instead bind to the ViewModel that was created solely for the purpose of Data Transfer to your view. On the ViewModel, you can create these fields as nullable decimals. You can then map the ViewModel back to your Domain Model however you like.

This is really the correct behavior. If you enter nothing in the TextBox then that is equivalent to null, not 0.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top