Fienix
Fienix

Reputation: 245

3 Models in one View with @foreach

I have an ASP.NET MVC 4 C# application and I want to display data from 3 different models in one view.

The schemas are related via foreign keys like this:

Model A | Model B | Model C
ID      | ID      | ID
          A_ID    | B_ID

In View for model A, I want to be able to to display data that is linked in B and C.

Right now, in the View for Model A (Details) I can do:

@model Application.Models.A

@foreach (var b Model.B)
    {
        @Html.DisplayFor(modelB => B.Title)
        <br />
    }

I want to be able to then do:

@foreach (var b Model.B)
    {
        @Html.DisplayFor(modelB => B.Title)

        @foreach (var c Model.B.C)
        {
            @Html.DisplayFor(modelC => C.Title)
            <br />
        }

        <br />
    }

You can do this in ruby on rails, how can I do this in MVC 4?

Upvotes: 1

Views: 130

Answers (2)

Fienix
Fienix

Reputation: 245

I figured it out.

I had the models, controllers and relationships setup correctly. I just needed to modify my view to the following:

@foreach (var b in Model.Bs)
    {
        @Html.DisplayFor(B => b.Title)
        <br />
        foreach (var c in b.Cs)
        {
            @Html.DisplayFor(C => c.Title)
            <br />
        }
    }

Thanks.

Upvotes: 0

Viraj Siriwardana
Viraj Siriwardana

Reputation: 41

If you are using any of the popular ORM tools (i.e.: Nhibernate, Entity Framework) you are able to model these relationship. In short after you model your above schema you will be able to pass an instance of Application.Models.A into your view. Because this type has the necessary relationships to the other entities.

But it is far more better to practice to create a separate view model, because passing entity models directly into views is not a good practice.

Upvotes: 1

Related Questions