How to create a View to insert multiple entities

Asked

Viewed 176 times

0

I have an entity that has daughter entities, such as: - Supplier (has main supplier data) - Suppliers - Supplier of telephones - Suppliers - etc....

Where each entity is a database table related to each other.

In MVC I created a Model for each entity and there arose a question.

To List, I will only use the main entity, but to insert a new record or edit an existing one, I will need my View to show all fields of all entities.

What better solution? - Create a View for each entity, and somehow call all views on the same page? - or create a view with only all entities?

In both cases, how do I implement these solutions?

  • Only with this it is difficult to answer, it seems to me that it is the case for a view only and does not have to call any other, but it depends on the UI you want, the intended UX.

2 answers

2


your view:

public class FornecedorViewModel 
{
    public FornecedorViewModel()
    {
        FornecedorEmails = new List<FornecedorEmailsViewModel>();
        FornecedorTelefones = new List<FornecedorTelefonesViewModel>();
        FornecedorEnderecos = new List<FornecedorEnderecosViewModel>();
    }
    //suas outras props aqui..

    public virtual IEnumerable<FornecedorEmailsViewModel> FornecedorEmails { get; set; }
    public virtual IEnumerable<FornecedorTelefonesViewModel> FornecedorTelefones { get; set; }
    public virtual IEnumerable<FornecedorEnderecosViewModel> FornecedorEnderecos { get; set; }
} 

for the listing screen, if the screen is only a list of forencers, you should type your view as follows:

@model IEnumerable<FornecedorViewModel>

for screens where you need only 1 Vendor, but with its child attributes, type as below:

@model FornecedorViewModel

It is worth mentioning that the differential will be where you take the data (in this case a repository). You must bring only Vendor data on the listing screen, while on the other, you must bring the results of Vendor and its child classes.

To access Vendor’s child properties in your view, simply call Model (with a capital M) and from there, you will navigate to any daughter entity. Example:

@Model.FornecedorEmails

Note: this is just a view. You can implement in N different ways.

  • 1

    thank you very much! that’s just what I needed!

0

Well, I would create a new model obterFornecedoresModel With the definitions of other models. Type public IEnumerable<Fornecedor> Fornecedores{ get; set; } And so on with the other entities.

With this I would only have a view, with a model, and I would do all the interactions in the controller. I don’t know if it’s the best way, but I think it helps.

Browser other questions tagged

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