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.

4

2 回答 2

0

为什么不使用模型本身:

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

或者一个可以使用

@foreach (var item in Model)
{
    @Html.Display(item.UserName)
}
于 2014-03-19T14:25:28.710 回答
0

DisplayFor需要一个表达式,该表达式标识包含要显示的属性的对象。HtmlHelper (=@Html) 已经给出了模型。因此,您不需要使用您的 item 变量。

于 2014-03-19T14:35:24.027 回答