Your question says that you are "calling ModelState.Validate" in your controller. There is no such method, so I assume you mean if (ModelState.IsValid) .
The first step in the process of model binding is that the parameters of your method are initialized, in your case, a new instance of FirstViewModel . Then the model values ββare set based on form data, route values, query string values, etc., And any validation errors associated with the properties of your model are added to ModelState .
Subsequently, changing the property value in your model does not affect ModelState , so if the initial value of month valid, then ModelState.IsValid will return true regardless of the setting viewModel.SecondViewModel.month = 13;
If you want to re-test your model, you need to use TryUpdateModel , which returns a bool indicating whether the update was successful
public HttpStatusCodeResult Create (FirstViewModel viewModel) { viewModel.SecondViewModel = new SecondViewModel(); viewModel.SecondViewModel.month = 13; if (TryUpdateModel(viewModel) { return new HttpStatusCodeResult(200); } else { return new HttpStatusCodeResult(304); } }
source share