我在互联网上搜索了2天,找到了我的问题的答案,但没有正确答案。
这些是我的课程
public class Player
{
public int ID { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public Team Team { get; set; }
public int TeamId { get; set; }
public class Team
{
public int TeamID { get; set; }
public string Name { get; set; }
public virtual List<Player> Players { get; set; }
我在我的视图模型中添加了相同的 - &gt;
public class CreatePlayerVM
{
public int ID { get; set; }
[Display(Name = "Last name")]
public string Name { get; set; }
[Display(Name = "First name")]
public string FirstName { get; set; }
[ForeignKey("TeamId")]
public Team Team { get; set; }
[Required]
[ForeignKey("Team")]
[Display(Name = "Team")]
public int TeamId { get; set; }
public class ListPlayerVM
{
public int ID { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
[ForeignKey("TeamId")]
public Team Team { get; set; }
public int TeamId { get; set; }
我对球员名单的看法是这样的 - &gt;
@Html.DisplayNameFor(model => model.Name)
@Html.DisplayNameFor(model => model.FirstName)
@Html.DisplayNameFor(model => model.Team)
@Html.DisplayNameFor(model => model.YellowCard)
@Html.DisplayNameFor(model => model.RedCard)
@Html.DisplayNameFor(model => model.Goal)
@foreach (var item in Model)
@Html.DisplayFor(modelItem => item.Name)
@Html.DisplayFor(modelItem => item.FirstName)
@Html.DisplayFor(modelItem => item.Team.Name)
@Html.DisplayFor(modelItem => item.YellowCard)
@Html.DisplayFor(modelItem => item.RedCard)
@Html.DisplayFor(modelItem => item.Goal)
和homeController
[HttpGet]
public ActionResult Players()
{
List<Player> p1 = Player.GetPlayers();
List<ListPlayerVM> p2 = new List<ListPlayerVM>();
foreach (Player p in p1)
{
p2.Add(new ListPlayerVM(p.ID, p.Name, p.FirstName, p.Team , p.TeamId, p.Goal, p.YellowCard, p.RedCard));
}
return View(p2);
}
和CreateController
[HttpPost]
public ActionResult CreatePlayer(CreatePlayerVM model)
{
if (ModelState.IsValid)
{
Player player = new Player(model.FirstName, model.Name, model.Team, model.TeamId ,0, 0, 0);
player.InsertPlayer();
}
PopulateTeamsDropDownList(model.TeamId);
return View(model);
}
如何在我创建的玩家列表中显示我的teamName?厌倦了在互联网上搜索,希望有人可以帮助我!
https://i.stack.imgur.com/5ELCJ.jpg
public static Player GetPlayer(int id)
{
using (LeagueDBContext ctx = new LeagueDBContext())
{
return ctx.Players.Where(a => a.ID == id).SingleOrDefault();
}
}
GRTS
答案 0 :(得分:1)
问题在于您不会懒得加载您的团队数据。您必须使用虚拟延迟加载它。您的播放器模型应如下所示:
public class Player
{
public int ID { get; set; }
public string Name { get; set; }
public string FirstName { get; set; }
public virtual Team Team { get; set; }
public int TeamId { get; set; }
}