ModelState.IsValid 在 ASP .NET Core 中总是返回 false

问题描述 投票:0回答:0

在我的案例中,我希望能够将图像上传到名为

Game
的实体。我使用
ModelView
作为实体,但每次我尝试创建一个新对象时,我总是以我的
ModelState
false
.

这是我的

Game
实体(它从
Id
继承
BaseEntity
属性)

public class Game : BaseEntity
    {
        public Game()
        {
            GameGenres = new HashSet<GameGenres>();
        }
        public string Name { get; set; }
        public string Description { get; set; }
        public double Price { get; set; }
        public int Quantity { get; set; }
        public string ImageURL { get; set; }
        public int CompanyID { get; set; }

        //to create connection with company entity 
        public Company Company { get; set; }

        //to create conenction with gameGenres
        public ICollection<GameGenres> GameGenres { get; set; }
        
        //To create connection with Reviews
        public ICollection<Review> Reviews { get; set; }
    }

这是我的模型视图

public int Id { get; set; }

   [Required]
   [MinLength(3)]
   [MaxLength(100)]
   public string Name { get; set; }

   [MaxLength(500)]
   public string Description { get; set; }

   [Required]
   [Range(0, double.MaxValue)]
   public double Price { get; set; }

   [Required]
   [Range(0, int.MaxValue)]
   public int Quantity { get; set; }

   [Required]
   public string? ImageURL { get; set; }

   [NotMapped]
   [DisplayName("Upload file")]
        
   public IFormFile ImageFile { get; set; }

   public int CompanyID { get; set; }
   [DisplayName("Genres")]
   public List<int>? GenreIds { get; set; }

最后这是我在控制器中创建新游戏的发布方法:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<IActionResult> Create([FromForm] GameViewModel game)
{
   if (ModelState.IsValid)
   {
      string wwwRootPath = _webHostEnvironment.WebRootPath;
      string fileName = Path.GetFileNameWithoutExtension(game.ImageFile.FileName);
      string extension = Path.GetExtension(game.ImageFile.FileName);

      fileName = fileName + DateTime.Now.ToString("yymmssfff") + extension;
      game.ImageURL = fileName;

      string path = Path.Combine(wwwRootPath + "/Image/", fileName);

      using (var fileStream = new FileStream(path, FileMode.Create))
      {
         await game.ImageFile.CopyToAsync(fileStream);
      }

      _context.Add(game);
      await _context.SaveChangesAsync();
      return RedirectToAction(nameof(Index));
   }
   ViewData["CompanyID"] = new SelectList(_context.Set<Company>(), "Id", "Id", game.CompanyID);

   return View(game);
}

调试时,我也试过使用Bind代替[FromFor],但都没有用。

我也在我的根目录中创建了一个文件夹,但我不知道为什么 ModelState.IsValid 总是错误的。提前致谢!

c# asp.net-mvc entity-framework
© www.soinside.com 2019 - 2024. All rights reserved.