0

A database I inherited stores multiple boolean values in a magic string. For example, the field PlantLocationString may have a value of "0, 1, 3" to indicate the record applies to manufacturing plants in Nebraska (0), Massachusetts (1) and Canada (3) but not to other locations California (2), Minnesota (4) etc. The poor design is repeated in multiple fields and I plan to leave the database unchanged.

To handle this oddity I created a ViewModel with boolean properties such as LocationNebraska = true, LocationCalifornia = false, etc. This ViewModel holds a reference to the source Model/Entity with the magic string field(s). In my controller I've added routines to convert the magic string to the appropriate boolean values and vice versa.

The problem is with ModelState and validation. PlantLocationString has a Required attribute yet only one or more boolean values needs to be selected (such as LocationNebraska). Check boxes in the View are bound to the ViewModel boolean fields. When the user checks "LocationNebraska" validation should succeed on HttpPost yet it fails - ModelState finds a null PlantLocationString field. Even after the controller populates PlantLocationString ModelState.IsValid remains false for that field.

How can I best handle this validation issue?

DeveloperDan
  • 4,626
  • 9
  • 40
  • 65
  • Sounds like you need to write a custom validation attribute: http://stackoverflow.com/questions/2280539/custom-model-validation-of-dependent-properties-using-data-annotations – Wurd Oct 03 '16 at 14:49
  • Why would have have the ViewModel propagating the bad design of the model? Recheck the design of your view model – Nkosi Oct 03 '16 at 14:53
  • Ideally I'd have database fields for each boolean checkbox Location. That's how I've made the ViewModel so I don't understand what you would have me change. – DeveloperDan Oct 03 '16 at 14:58
  • @DeveloperDan, You mention *ModelState finds a null PlantLocationString field*, implying that that field is on the ViewModel. – Nkosi Oct 03 '16 at 15:37
  • Yes - now I understand your point. My underlying Model is a property of the ViewModel. I did this because the Model has so many fields/properties. I hoped to avoid adding them all again to the ViewModel. The view razor controls are mostly bound to ViewModel.Model.Field except for the few controls bound to ViewModel.Field such as LocationNebraska. PlantLocationString is bound to no control in the view. – DeveloperDan Oct 03 '16 at 15:49

0 Answers0