views:

322

answers:

1

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?

+1  A: 

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.

Keith Rousseau
I'm actually using a ViewModel as a data transfer object already -- I'll edit the question to clarify. I'd have to refactor a lot of code to use nullable decimals however, and I was hoping to avoid that.
Brant Bobby
ViewModels aren't meant to be used across multiple Actions. You should have a new ViewModel for each Action that requires unique data. By using generic ViewModels across multiple actions, you will typically run into problems like the one you are experiencing.
Keith Rousseau