Daath
Daath

Reputation: 1979

How to validate multiple, separate models in a single ViewModel using ASP.NET MVC?

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

Upvotes: 0

Views: 2784

Answers (2)

Nicolas
Nicolas

Reputation: 29

This won't compile:

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

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

return View(vm)

Upvotes: 1

Midhun Mundayadan
Midhun Mundayadan

Reputation: 3182

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

Upvotes: 1

Related Questions