我是目前正在开发我的最后一年项目的最后一年学生,并遇到了一个我迄今无法弄清楚的问题。我试图在MyRosters视图中显示与团队ID列表相关的名单,但每当我尝试运行代码时,我得到的索引超出了数组的范围。错误。请有人帮帮我吗?
以下是ActionResult:
public ActionResult MyRosters()
{
string ClubName = Session["TeamName"].ToString();
var teams = db.Teams.Where(x => x.TeamName.Contains(ClubName) || ClubName == null).ToList();
int[] TeamID = new int[] { };
int i = 0;
foreach (Team t in teams)
{
TeamID[i] = t.TeamID;
i++;
}
return View(db.Rosters.Where(x => x.TeamID.Equals(TeamID) || ClubName == null).ToList());
}
以下是MyRosters视图:
@model MunsterAdministrator.Models.Roster
@{
ViewBag.Title = "MyRosters";
}
<h2>MyRosters</h2>
<table class="table table-condensed">
<tr>
<th>
@Html.DisplayNameFor(model => model.Team.TeamName)
</th>
<th>
@Html.DisplayNameFor(model => model.Fixture.FixtureID)
</th>
<th>
@Html.DisplayNameFor(model => model.Player1)
</th>
<th>
@Html.DisplayNameFor(model => model.Player2)
</th>
<th>
@Html.DisplayNameFor(model => model.Player3)
</th>
<th>
@Html.DisplayNameFor(model => model.Player4)
</th>
<th>
@Html.DisplayNameFor(model => model.Player5)
</th>
<th>
@Html.DisplayNameFor(model => model.Player6)
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Team.TeamName)
</td>
<td>
@Html.DisplayFor(modelItem => item.Fixture.FixtureID)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player1)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player2)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player3)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player4)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player5)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player6)
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
@Html.DisplayFor(modelItem => item.Player7)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player8)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player9)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player10)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player11)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player12)
</td>
</tr>
<tr>
<td></td>
<td></td>
<td>
@Html.DisplayFor(modelItem => item.Player13)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player14)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player15)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player16)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player17)
</td>
<td>
@Html.DisplayFor(modelItem => item.Player18)
</td>
</tr>
<tr>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.RosterID })
</td>
<td>
@Html.ActionLink("Details", "Details", new { id = item.RosterID })
</td>
<td>
@Html.ActionLink("Delete", "Delete", new { id = item.RosterID })
</td>
</tr>
}
非常感谢您提供给我的任何帮助,谢谢!
答案 0 :(得分:0)
您的数组没有元素,您无法为其第0个元素分配任何值。使用这个
int[] TeamID = teams.Select(b=>b.TeamID).toArray();
而不是这个
int[] TeamID = new int[] { };
int i = 0;
foreach (Team t in teams)
{
TeamID[i] = t.TeamID;
i++;
}