0

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

Daath
  • 1,899
  • 7
  • 26
  • 42
  • 1
    You should also include `[Required]` on both properties in class `TheViewModel`. Also what is the value of `TheCode` when you say that the `ModelState.IsValid` returns true when it should not? Finally ou should pass variable `vm` to the `View` method as a View takes 1 model not multiple models. – Igor Jul 05 '16 at 20:25

2 Answers2

1

you only need to pass vm only to view . model binding happening with one model only.if you want to pass multiple model in this case youhave to use Dynamic objects like ViewBag etc.....

 return View(vm);

Then you can bind View Model With you View.The code which you given will not run return View(vm.ModelAExample, vm.ModelBExample)); here it will throw syntax error

Best Practices ViewModel Validation in ASP.NET MVC

Community
  • 1
  • 1
MMM
  • 3,132
  • 3
  • 20
  • 32
1

This won't compile:

return View(vm.ModelAExample, vm.ModelBExample));

If you use vm as ViewModel, the validation will be correct:

return View(vm)
Nicolas
  • 29
  • 3