我有三节课。在我的创建视图中,我得到了一个加载所有FootballTeam的下拉列表。 但问题是当我发布到控制器时。因为ModelState.IsValid无效。我知道它与“公共虚拟FootballTeam FootballTeam {get; set;}”有关,因为它在我添加之前有效:)
我唯一想做的就是将玩家绑定到fotballs团队。我可以将我的“公共虚拟FootballTeam FootballTeam”更改为int而不是虚拟FootballTeam,这应该可行。 但我在这个Entity Framework one to many上看到,这是映射它的最佳方式,就像我使用虚拟FootballTeam一样。
[HttpPost]
public ActionResult CreatePlayer(PlayerViewModel playerViewModel)
{
var team = db.FootballTeam.Find(playerViewModel.Player.FootballTeam.Id);
playerViewModel.Player.FootballTeam = team;
if (ModelState.IsValid)
{
db.Player.Add(playerViewModel.Player);
db.SaveChanges();
return RedirectToAction("Teams");
}
return RedirectToAction("Teams");
}
@model test.Models.PlayerViewModel
@Html.DropDownListFor(x => x.Player.FootballTeam.Id, Model.FootballTeams.Select(y => new SelectListItem
{
Text = y.Name,
Value = y.Id.ToString()
}))
public class Player
{
public int Id { get; set; }
public int ImageId { get; set; }
[Required(ErrorMessage = "Vänligen ange ett namn")]
public string Name { get; set; }
[Required(ErrorMessage = "Vänligen ange en possition")]
public string Position { get; set; }
[Required(ErrorMessage = "Vänligen ange födelseåret")]
public string BirthYear { get; set; }
[Required(ErrorMessage = "Vänligen ange en längd")]
public string Length { get; set; }
[Required(ErrorMessage = "Vänligen ange en vikt")]
public string Weight { get; set; }
[Required(ErrorMessage = "Vänligen ange moderklubben, alt ett '-'")]
public string FirstClub { get; set; }
public virtual FootballTeam FootballTeam { get; set; }
}
public class FootballTeam
{
public int Id { get; set; }
[Required(ErrorMessage = "Vänligen ange ett namn")]
public string Name { get; set; }
public ICollection<Player> Players { get; set; }
public ICollection<Coach> Coaches { get; set; }
[Required(ErrorMessage = "Vänligen fyll i information om laget")]
[DataType(DataType.MultilineText)]
public string Information { get; set; }
}
public class PlayerViewModel
{
public Player Player { get; set; }
public IEnumerable<Image> Image { get; set; }
public IEnumerable<FootballTeam> FootballTeams { get; set; }
}