WhiskerBiscuit
WhiskerBiscuit

Reputation: 5157

Why is DisplayForModel not showing the expected output?

I have a simple razor page, where the first part correctly shows information from each element in my model in a table. After that I'm trying to use DisplayFor to show me every property in the model, but it generates 123 for each iteration. What am I doing wrong?

@model System.Data.Entity.IDbSet<DBFramework.MyPerson>
@{
    ViewBag.Title = "Home Page";
}
<p></p>
<table border="1">
    <thead>
        <tr>
            <th style="width:300px;">Name</th>
            <th style="width:300px;">Age</th>
        </tr>
    </thead>
    @foreach (var p in Model)
    {
        <tr>
            <td>@Html.Label(p.Name)</td>
            <td>@Html.Label(p.Age.ToString())</td>
        </tr>
    }
</table>

@foreach (DBFramework.MyPerson x in Model)
{
    @Html.DisplayForModel(x)<br/>
}

Creates the following output:

Name  Age
Mike  40 
Penny  1 
Kunal  30 

123
123
123 

Upvotes: 0

Views: 455

Answers (2)

Karhgath
Karhgath

Reputation: 1809

DisplayFor and DisplayForModel are used with templates in Views\Shared\DisplayTemplates.

When you call DisplayForModel, it will take the page model (Model) and if you specify a parameter, will try to load the template with the name provided (if string) or add the object as additional data in ViewData. When you called:

@foreach (DBFramework.MyPerson x in Model)
{
    @Html.DisplayForModel(x)<br/>
}

You told it - Display Model which is type System.Data.Entity.IDbSet<DBFramework.MyPerson> and add MyPerson in the template ViewData. Do this 3 times. You also didn't give him a hint to select a DisplayTemplate and it will try to use convention to find it.

As Bappi Datta said, if you want to display a template for MyPerson, you need to call:

@foreach (var item in Model)
{
    @Html.DisplayFor(model => item)
}

However, you need a MyPerson display template created which accepts @model DBFramework.MyPerson to render the item or it will simply do a .ToString() by default I believe.

Upvotes: 1

Bappi Datta
Bappi Datta

Reputation: 1380

Try this:

@foreach (var item in Model)
    {
        @Html.DisplayFor(model => item)
    }

Upvotes: 2

Related Questions