我有三个班。在我的创建视图中,我有一个加载所有 FootballTeam 的下拉列表。但问题是当我发布到控制器时。因为 ModelState.IsValid 无效。我知道它与“公共虚拟 FootballTeam FootballTeam { get; set; }”有关,因为它在我添加它之前就起作用了:)
我唯一想做的就是将一名球员绑定到一支足球队。我可以将我的“公共虚拟 FootballTeam FootballTeam”更改为 int 而不是虚拟 FootballTeam,这应该可以工作。但我在这个实体框架上一对多地看到它是映射它的最佳方式,就像我对虚拟 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; }
}