How to use multiple models in a view

Asked

Viewed 1,457 times

7

I’m doing a criminal record and I have the following models:

  • Pessoa
  • Fisica
  • Juridica

And in the code of mine view I have only the declaration of a model:

@model CodeFirst.Models.Fisica

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

1 answer

10


That is one of the reasons why a view model is used, a view model is a model which should be used exclusively to encapsulate data that will be sent to the view. So instead of you sending one model directly to the view, you encapsulate him inside a view model along with other data you want to view have access.

In your case, what could be done is the following, you would create a class inside the folder /Models of your project following the [NomeDaViewOndeSeráUtilizada]ViewModel and within this class you would create a property for each of these models. Take an example:

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

And the action who would return this view model could turn out 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);
}
  • I know more the Webforms and had is doubtful too. I could say that another way would be using partialView?

  • 1

    @Marconi yes, another way could be using a partial view, but the situation would have to be analyzed further, this because a partial view is generally used to avoid code repetition, i.e., a partial view will usually be used in more than one place in the application, and another point worth noting is that you will still need to send a model to the partial view as one of the parameters to call it from within your view and this model can be obtained through view model of view or manually unstable from within the view.

  • Okay, thank you. Good answer.

  • 1

    Thanks @Zignd, it worked perfectly!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.