ASP.NET Core中添加Games属性后Tournament的Create方法失效
问题:添加ICollection属性后Tournament的Create Action失效
在.NET 7开发ASP.NET Core Web应用时,给Tournament类添加public ICollection<Game> Games { get; set; }属性后,Tournament的Create Action完全失效——提交表单只会刷新页面,根本不会执行数据创建操作。已经尝试过替换教程中的代码、移除实体类的Required特性,但问题依然存在。
问题代码行
public ICollection<Game> Games { get; set; }
相关实体类代码
using System.ComponentModel.DataAnnotations; namespace WebApplication3.Models { public class Tournament { public int TournamentId { get; set; } [Required] public string TournamentName { get; set; } [Required] public string Location { get; set; } //public DateTime StartDate { get; set; } //public DateTime EndDate { get; set; } public ICollection<Game> Games { get; set; } } } namespace WebApplication3.Models { public class Game { public int GameId { get; set; } //public DateTime GameDate { get; set; } public string Player1 { get; set; } public string Player2 { get; set; } public string Score { get; set; } public int TournamentId { get; set; } public Tournament Tournament { get; set; } } }
Tournament的Create Action代码
public IActionResult Create() { return View(); } // POST: Tournament/Create // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("TournamentId,TournamentName,Location")] Tournament tournament) { if (ModelState.IsValid) { _context.Add(tournament); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } return View(tournament); }
Game的Create Action代码
public IActionResult Create() { ViewData["TournamentId"] = new SelectList(_context.Tournament, "TournamentId", "TournamentId"); return View(); } // POST: Game/Create // To protect from overposting attacks, enable the specific properties you want to bind to. // For more details, see http://go.microsoft.com/fwlink/?LinkId=317598. [HttpPost] [ValidateAntiForgeryToken] public async Task<IActionResult> Create([Bind("GameId,Player1,Player2,Score,TournamentId")] Game game) { if (ModelState.IsValid) { _context.Add(game); await _context.SaveChangesAsync(); return RedirectToAction(nameof(Index)); } ViewData["TournamentId"] = new SelectList(_context.Tournament, "TournamentId", "TournamentId", game.TournamentId); return View(game); }
内容的提问来源于stack exchange,提问作者TJ_Frags
相关产品推荐
相关产品推荐

