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()たが、ビューのviewModelを取得しているようです(私の場合は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> 

表示テンプレートの名前と場所に注意してください。これを機能させたい場合は、この規則を尊重することが重要です。

于 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>
}

ViewModel2のDisplayModelを変更しないでください。ビューでは、次のように呼び出すことができます。

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