what would I use in this situation(asp.net mvc 3 display templates)

假装没事ソ 提交于 2019-12-11 16:28:05

问题


I have something like this

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>

I tried to use "@Html.DisplayForModel()" but that I seems to take the viewModel of the view(so in my case ViewModel1)

I need to make it take ViewModel2 but I don't see any option to pass in ViewModel2(a model object).

I then tried

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

That did not work to well it just printed out like the first properties value and never even made any cells.

Here is basically my display template

@model ViewModel2

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

So how can I make this work?


回答1:


Try like this:

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

and then inside ~/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.




回答2:


If you REALLY don't want the foreach in your "main" template, you can tag your property with UIHint

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

Then, in DisplayTemplates\ListOfViewModel2.ascx, you put your foreach

@model IList<ViewModel2>

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

Dont change your DisplayModel for ViewModel2, and in you view, you can call

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


来源:https://stackoverflow.com/questions/5531836/what-would-i-use-in-this-situationasp-net-mvc-3-display-templates

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!