0

I am trying to use a display template (Pet.cshtml), which I have placed in ~/Views/Shared/DisplayTemplates, as per convention.

The Index action gets the IEnumerable and passes it to Index.cshtml, which passes it along to _PetTablePartial. So far, so good. However, when Html.DisplayForModel is called, I get this error:

The model item passed into the dictionary is of type 'Pet', but this dictionary requires a model item of type 'System.Collections.Generic.IEnumerable`1[Pet]'. 

But I (think) I can clearly see that the model item is in fact an IEnumerable. What am I doing wrong?

Controller: 

public ActionResult Index()
{
  return View(pet.GetPets()); // returns IEnumerable<Pet>
}

Index.cshtml:

@model IEnumerable<Pet>
{Html.RenderPartial("_PetTablePartial", Model);}
...

_PetTablePartial.cshtml:

@model IEnumerable<Pet>
@Html.DisplayForModel()

~/Shared/DisplayTemplates/Pet.cshtml:
@model IEnumerable<Pet>

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

2 回答 2

1

Pet.cshtml 应该有一个 Pet 的模型类型,因为您在这里只处理一个宠物。

DisplayTemplates 自动枚举集合,并使用单个项目调用您的 DisplayTemplate。这是他们的好处之一。你不需要做任何枚举。

只需将 Pet.cshtml 的类型更改为 Pet

我还怀疑您不想为每只宠物单独使用一张桌子。所以你想要的是在你的局部视图中创建表和标题,然后在 Pet.cshtml 中只有一个数据行,因为 Pet.cshtml 将被多次调用,每行一次。

PetTablePartial.cshtml:

@model IEnumerable<Pet>

<table>
    <tr>
        <th> Pet Name </th>
    </tr>
   @Html.DisplayForModel()
</table>

~/Shared/DisplayTemplates/Pet.cshtml:

@model Pet

<tr>
    <td>@Html.DisplayFor(x => x.Name)</td>
</tr>
于 2014-05-17T17:30:10.983 回答
0

在 Pet.cshtml 中,您传入IEnumerable<Pet>,但随后尝试访问Name模型的属性。IEnumerable没有Name财产。

一般来说,你会用一个 foreach 循环来包装它,这样你就可以访问Name列表中元素的属性。但是,由于您正在尝试写出表头,因此您只想写出一次而不遍历列表。

看看这些其他 SO 问题:

于 2014-03-20T18:21:14.150 回答