How to use multiple models in a view

6

I am doing an individual registration and I have the following models:

  • Pessoa
  • Fisica
  • Juridica

In my view code, I only have the declaration of a model :

@model CodeFirst.Models.Fisica

The problem is that when I make a registration within my view , it will be necessary for me to have access to the 3 models listed above. How do I access them?

    
asked by anonymous 23.11.2015 / 11:59

1 answer

9

This is one of the reasons a view model is used, a view model is a model that should be used exclusively to encapsulate data that will be sent to the view . So instead of sending a model directly to the view , you encapsulate it inside a view model along with other data you want view has access.

In your case, what could be done is as follows, you would create a class inside the /Models folder of your project following the [NomeDaViewOndeSeráUtilizada]ViewModel pattern and within that class you would create a property for each of those models . Here's an example:

public class IndexViewModel
{
    public Pessoa Pessoa { get; set; }
    public Fisica Fisica { get; set; }
    public Juridica Juridica { get; set; }
}

And the action that would return this view model might look like this:

public ActionResult Index()
{
    var viewModel = new IndexViewModel();

    // Preencha as propriedades do objeto viewModel como desejar
    // e o retorne para a view

    return View(viewModel);
}
    
23.11.2015 / 12:12