radbyx
radbyx

Reputation: 9670

How do i show a list from a model to another View in ASP.NET MVC 4

I have a list of Topic's. Each Topic have a list of Message. When i click on "Details" I want to open a new View that display a list of the Message's from the Topic.

I expect that I need to modify this line: (this is what I have so far)

@Html.ActionLink("Details", "Details", new { id=item.Id }, null)

The Message's are accessed by item.Message.

And the first line in the Detail View

@model IEnumerable<Models.TopicMessage>


This is my Topic View:

@model IEnumerable<Models.Topic>

<table>
    <tr>
        <th>
            @Html.DisplayNameFor(model => model.Name)
        </th>
        <th></th>
    </tr>

@foreach (var item in Model) {
    <tr>
        <td>
            @Html.DisplayFor(modelItem => item.Name)
        </td>
        <td>
            @Html.ActionLink("Details", "Details", new { id=item.Id }, null)
        </td>
    </tr>
}

</table>

Upvotes: 1

Views: 1514

Answers (2)

radbyx
radbyx

Reputation: 9670

I fixed this by making a somethingViewModel that contained both the liste and the Id. That way i could contain the two information from two difference places in one new object I had access to in the View.

Upvotes: 0

p.s.w.g
p.s.w.g

Reputation: 149060

There are a number of ways to do that. You can use the Action method to execute the controller action directly:

<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.Action("Details", "Details", new { id=item.Id })
    </td>
</tr>

Or you can bypass the controller and render the view directly using this overload of DisplayFor:

<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Messages, "MessagesDetail")
    </td>
</tr>

Or if you define the template as the default DisplayTemplate, you can just do this:

<tr>
    <td>
        @Html.DisplayFor(modelItem => item.Name)
    </td>
    <td>
        @Html.DisplayFor(modelItem => item.Messages)
    </td>
</tr>

Upvotes: 1

Related Questions