C# ASP.NETMVC在ove视图中的两个模型,代码更改
我有这个代码,它工作得很好:C# ASP.NETMVC在ove视图中的两个模型,代码更改,c#,asp.net,asp.net-mvc,C#,Asp.net,Asp.net Mvc,我有这个代码,它工作得很好: @model IEnumerable<Moviestore.Models.Movie> @{ ViewBag.Title = "Index"; } <p> @Html.ActionLink("Create New", "Create") </p> <table class="table"> <tr> <th> @Html.DisplayNameFor(model =&g
@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 var项
然后@Html.DisplayFormodelItem=>item.Title也需要一些更改
很抱歉发了这么长的帖子,我尽可能地解释了这个问题。正如我在评论中提到的,处理这种情况的适当方法是在特定的视图页面上使用一个包含您需要查看的模型的ViewModel 不过,为了回答您的特定问题,您可以通过位置访问元组的每个项,例如,如果您的模型是元组,则可以通过model.Item1访问电影对象,通过model.Item2访问用户对象,等等
但我强烈建议您采用我链接的ViewModel方法。您好,以下是符合您要求的ViewModel:
public class MovieUserViewModel
{
public IEnumerable<Movie> Movie { get; set; }
public IEnumerable<Users> Users { get; set; }
}
其他信息:
谢谢
Karthik处理在特定视图页面上需要多个模型的情况的适当方法是使用包含所需模型的ViewModel。是的。如果要在视图中使用模型m1和m2,请创建另一个模型vm,该模型vm具有m1和m2的成员。
@foreach (var item in Model.Movie)
@foreach (var item in Model.Users)