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

1
  • 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. Commented Jul 5, 2016 at 20:25

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

Comments

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.