How to pass properties of another model?

Asked

Viewed 162 times

0

Problem: I have an index that uses a model of the type:

    @model IEnumerable<projeto.Models.classe1>

I need to access some properties of classe 2, my classe1 being Ienumerable, how can I access the properties of classe 2?

I tried to pass: Classe1 classe1 {get; set;}.

But when I call the field model.classe1.NomeCampo it does not let because that page uses the Ienumerable type of classe 1.

Ideal Scenario: I’d like to access this classe 2 through the model classe 1.

1 answer

0


Do your classes relate? You can create a Viewmodel that contemplates your Models. Inside the controller you handle the loading of this Viewmodel doing the mapping due from your models to Viewmodel. For example, say you want to display a list of two classes. Your viewModel would have to look something like this:

public class ClasseViewModel
{
    public Classe1 classe1 { get; set; }
    public Classe2 classe2 { get; set; }
}

In View you would access like this:

@model IEnumerable<projeto.ViewModel.ClasseViewModel>

You can treat as you like by putting in a Ienumerable:

public class ClasseViewModel
{
    public IEnumerable<Classe1> classe1 { get; set; }
    public Classe2 classe2 { get; set; }
}

In View Access the same way:

@model IEnumerable<projeto.ViewModel.ClasseViewModel>

However, in this case, to access the Classe1 data, you need to perform a @foreach on Razor to read all the items in your Ienumerable:

@foreach(var item in Model.classe1){
   @Html.Raw(item.atributo);
}

Browser other questions tagged

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