在这种情况下我会使用什么(asp.net mvc 3 显示模板)
我有类似的东西
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>
那么我该如何使其工作呢?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
尝试如下:
然后在
~/Views/Shared/DisplayTemplates/ViewModel2.cshtml
内:注意显示模板的名称和位置。如果你想让它发挥作用,尊重这个约定很重要。
Try like this:
and then inside
~/Views/Shared/DisplayTemplates/ViewModel2.cshtml
:Notice the name and location of the display template. It is important to respect this convention if you want this to work.
如果你真的不想在你的“主”模板中使用 foreach,你可以用 UIHint 标记你的属性
然后,在 DisplayTemplates\ListOfViewModel2.ascx 中,你把你的 foreach
不要改变 ViewModel2 的 DisplayModel,在你的视图中,你可以称呼
If you REALLY don't want the foreach in your "main" template, you can tag your property with UIHint
Then, in DisplayTemplates\ListOfViewModel2.ascx, you put your foreach
Dont change your DisplayModel for ViewModel2, and in you view, you can call