什么会我在这种情况下使用(asp.net MVC 3个显示模板)(what would I use

2019-10-30 00:23发布

我有这样的事情

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>   

那么,如何使这项工作?

Answer 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> 

注意显示模板的名称和位置。 如果你想要这个工作是很重要的,尊重这个约定。



Answer 2:

如果你真的不想在你的“主”模板的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)


文章来源: what would I use in this situation(asp.net mvc 3 display templates)