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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With