0

我有这样的东西

public class ViewModel1
{
   // some properties here
   public List<ViewModel2> ViewModel2 {get; set;}
}

public class ViewModel2
{
   public string A {get; set;}
   public string B {get; set;}
}

// view

<table>
  <thead>
     <tr> a </tr>
     <tr> b </tr>
  </thead>
   <tbody>
      // want to use a display template to render table row and cells so I don't need to use for loop 
   </tbody>
</table>

我尝试使用“ @Html.DisplayForModel()”,但我似乎采用了视图的视图模型(所以在我的例子中是 ViewModel1)

我需要让它采用 ViewModel2,但我看不到任何传入 ViewModel2(模型对象)的选项。

然后我尝试了

 @Html.DisplayFor(x => x.ViewModel2)

这并没有很好地工作,它只是像第一个属性值一样打印出来,甚至从未制作任何单元格。

这里基本上是我的显示模板

@model ViewModel2

  <tr>
        <td>@Model.A</td>
        <td>@Model.B</td>
 </tr>   

那么我怎样才能使这项工作呢?

4

2 回答 2

1

试试这样:

<table>
    <thead>
        <tr>
            <th>a</th>
            <th>b</th>
        </tr>
    </thead>
    <tbody>
        @Html.DisplayFor(x => x.ViewModel2)
    </tbody>
</table>

然后在里面~/Views/Shared/DisplayTemplates/ViewModel2.cshtml

@model ViewModel2
<tr>
    <td>@Model.A</td>
    <td>@Model.B</td>
</tr> 

Notice the name and location of the display template. It is important to respect this convention if you want this to work.

于 2011-04-04T06:17:15.047 回答
0

如果您真的不希望在“主”模板中使用 foreach,则可以使用 UIHint 标记您的属性

public class ViewModel1
{
   // some properties here
   [UIHint("ListOfViewModel2")]
   public List<ViewModel2> ViewModel2 {get; set;}
}

然后,在 DisplayTemplates\ListOfViewModel2.ascx,你把你的 foreach

@model IList<ViewModel2>

foreach( var m in Model )
{
    <tr>@Html.DisplayFor(x => m)</tr>
}

不要将您的 DisplayModel 更改为 ViewModel2,在您看来,您可以调用

@Html.DisplayFor(x => x.ViewModel2)
于 2011-04-03T19:42:39.243 回答