2

I would like to display a list of items in a View using Html.DisplayModelFor().

Here is the controller:

public ActionResult Index() {

        var person = new ApplicationUser();
        person.Email = "Greg@gmail.com";
        person.UserName = "Greg";

        var person2 = new ApplicationUser();
        person.Email = "Gary@gmail.com";
        person.UserName = "Gary";

        var list = new List<ApplicationUser>();
        list.Add(person);
        list.Add(person2);

        return View(list);
    }

Here is the view:

@model  IEnumerable<WebApplication32.Models.ApplicationUser>


@Html.DisplayForModel()

Here is the DisplayTemplate named ApplicationUser:

@model WebApplication32.Models.ApplicationUser
<div>
  @Html.DisplayFor(u=> u.UserName)
  @Html.DisplayFor(u=> u.Email)
</div>

The result is only the first item being displayed.

If I change the view to:

@model  IEnumerable<WebApplication32.Models.ApplicationUser>

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

Then each item is displayed.

But the second view makes no sense to me: In the foreach, 'item' does not appear to be used. Yet it is looping through the items.

Greg Gum
  • 33,478
  • 39
  • 162
  • 233
  • Possible duplicate of this: http://stackoverflow.com/questions/8002059/asp-net-mvc-display-template-for-a-collection By the way, the method's name is `DisplayForModel()`, not `DisplayModelFor()`. – ataravati Mar 19 '14 at 14:53

2 Answers2

0

Why do not use model's itself:

@foreach (var item in Model)
{
    <label>@item.UserName</label>
    <label>@item.Email</label>
}

Or one can use

@foreach (var item in Model)
{
    @Html.Display(item.UserName)
}
Jeyhun Rahimov
  • 3,769
  • 6
  • 47
  • 90
  • Because the actual page has a number of different collections and I want to be able to use a DisplayTemplate/EditTemplate for each one. – Greg Gum Mar 19 '14 at 14:28
0

DisplayFor expects an expression that identifies the object that contains the properties to display. The Model is already given by the HtmlHelper (=@Html). Therefor you don't need to use your item variable.

user2900970
  • 751
  • 1
  • 5
  • 24