6

Let's just say I have A ViewModel that is made up of 3 other ViewModels. One contains a list of items, the other contains an instance of a class with a [Required] attribute and then another list of other items.

If the user selects from one of the items in either of the two lists, I do not want the [Required] attribute on the 2nd object to cause the ModelState to be invalid, because if the user selects one of those items they won't need to fill out the form with the item with the [Required] attribute.

How can I solve this problem?

ewahner
  • 1,149
  • 2
  • 11
  • 23

1 Answers1

5

One option is for you to remove the "offending" validation by using ModelState.Remove("KeyName"). I have exactly the same scenario and have implemented the following:

var MyModel = _someService.GetModelById(id);
TryUpdateModel(MyModel);
ModelState.Remove("MyModel.OffendingField");
if (ModelState.IsValid)
{
    ...
}

It is important though that you make sure this will not have a knock-on effect in other areas of your code.

Ozzy
  • 964
  • 1
  • 10
  • 21
  • I think instead of validating the entire ViewModel, I will do as you suggest and conditionally validate the Models that are affected by the users selection. Moreover, this made me rethink the application design and thankfully I have found a few better ways of handling it so that this is less of an issue. – ewahner Apr 11 '11 at 12:03