So I have two separate models: ModelA
and ModelB
. I also have a ViewModel: TheViewModel
. TheViewModel
contains an instance of ModelA
as well as ModelB
.
ModelA
and ModelB
have their own respective properties and [Required
]s. However, when I go to post the form, TheViewModel
only validates ModelA
and ignores ModelB
How can I validate multiple models using one ViewModel?
Some code snippets:
ModelA
public class ModelA
{
[Required]
public string TheID { get; set; }
public string TheName { get; set; }
}
ModelB
public class ModelB
{
[Required]
public string TheCode { get; set; }
public string TheType { get; set; }
}
TheViewModel
public class TheViewModel
{
public ModelA ModelAExample { get; set; }
public ModelB ModelBExample { get; set; }
}
Controller
[HttpPost]
[ValidateAntiForgeryToken]
public IActionResult Create(TheViewModel vm)
{
if (ModelState.IsValid)
{
return RedirectToAction("Index", "Home");
}
return View(vm.ModelAExample, vm.ModelBExample));
}
The ModelState will only validate if the TheID
property in ModelA
is valid, and not TheCode
in ModelB