Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

MVC 3 ModelState.IsValid with multiple ViewModels

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?

like image 205
ewahner Avatar asked Apr 06 '11 03:04

ewahner


1 Answers

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.

like image 88
Ozzy Avatar answered Nov 12 '22 15:11

Ozzy