Reputation: 9963
I want to do some conditional validation for a view model I have created.
public class MyViewModel
{
public int SelectedItem { get; set; }
public Item Item1 { get; set; }
public DetailedItem Item2 { get; set; }
}
public class Item
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
}
public class DetailedItem
{
[Required]
public int Id { get; set; }
[Required]
public string Name { get; set; }
[Required]
public string Description { get; set; }
}
I have a radiobutton bound to SelectedItem that via clientside shows or hides a partial view bound to Item & DetailedItem.
On form post I want to validate the selected model but how. If I were to use the above code and do a
ModelState.IsValid
With only one of the partial views fully completed I would get a IsValid=false due to the other modal not containing the required fields.
Is there a way to only validate only the selected model?
Any help would be awesome!
Upvotes: 1
Views: 150
Reputation: 1863
Yes, the ModelState is a Dictionary class and you can remove an item from it using a Key.
For example,
ModelState.Remove("Item1");
Then a call to
ModelState.IsValid
will ignore requirements of that entry.
Here is a link to the documentation, and there is also some discussion about whether this should ever occur in your ViewModels or not.
Upvotes: 2