I'm trying to only check one model with ModelState.IsValid
once, after that I want to check another model with ModelState.IsValid
and I want to do it all in one action.
Let me show to you what I really want to do below:
[AllowAnonymous]
[HttpPost]
public async Task<IActionResult> FillingInformation(Company company, Agency agency, List<IFormFile> files, Address address)
{
if (ModelState.IsValid("Company"))//if its possible
{
//.....
}
else if (ModelState.IsValid("Agency"))//if its possible
{
//.....
}
else if (ModelState.IsValid("Address"))//if its possible
{
//.....
}
else
{
//.....
}
}
I already searched and tried to apply it to my code such as things like: GetFieldValidationState
, ValidationState
and Microsoft.AspNetCore.Mvc.ModelBinding.ModelValidationState
but I just could not apply them well.
I tried to write an extension method which checks ModelState.IsValid
but it still checking both models not one.
i am using something like this.
try {
var context = new ValidationContext(Company, serviceProvider: null, items: null);
var results = new List<ValidationResult>();
if (!Validator.TryValidateObject(Company, context, results, true))
throw new Exception("Check Company info...");
//validate all models
}
catch (Exception e) {
ModelState.AddModelError("", e.Message);
return View("your_view");
}