【发布时间】:2017-12-12 06:42:34
【问题描述】:
我有这段代码,它运行良好:
@model IEnumerable<Moviestore.Models.Movie>
@{
ViewBag.Title = "Index";
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Title)
</th>
<th>
@Html.DisplayNameFor(model => model.Genre)
</th>
<th>
@Html.DisplayNameFor(model => model.Author)
</th>
<th>
@Html.DisplayNameFor(model => model.Year)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
if (item.IsDeleted == 0)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Year)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
@Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
</td>
</tr>
}
}
</table>
但我需要再添加一个模型,我用 Tuple 这样做了:
@using Moviestore.Models;
@model Tuple<Movie, User>
@{
ViewBag.Title = "Index";
}
<p>
@Html.ActionLink("Create New", "Create")
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(tuple => tuple.Item1.Title)
</th>
<th>
@Html.DisplayNameFor(tuple => tuple.Item1.Genre)
</th>
<th>
@Html.DisplayNameFor(tuple => tuple.Item1.Author)
</th>
<th>
@Html.DisplayNameFor(tuple => tuple.Item1.Year)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
if (item.IsDeleted == 0)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Title)
</td>
<td>
@Html.DisplayFor(modelItem => item.Genre)
</td>
<td>
@Html.DisplayFor(modelItem => item.Author)
</td>
<td>
@Html.DisplayFor(modelItem => item.Year)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.MovieID }) |
@Html.ActionLink("Details", "Details", new { id = item.MovieID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.MovieID })
</td>
</tr>
}
}
</table>
但现在我的下半部分代码有问题。 来自@foreach
我不知道我需要放什么来代替@foreach(Model中的var item)
然后@Html.DisplayFor(modelItem => item.Title) 也需要一些改动。
抱歉,帖子太长了,我已尽我所能解释问题。
【问题讨论】:
-
处理这种情况(在特定视图页面上需要多个模型)的适当方法是使用包含所需模型的 ViewModel。
-
是的。如果您想在视图中使用模型 m1 和 m2,请创建另一个模型 (vm),其中包含 m1 和 m2 的成员。
标签: c# asp.net asp.net-mvc