Вопрос

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.

Это было полезно?

Решение

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.

Другие советы

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)
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top