ayhan
ayhan

Reputation: 1

ModelState.IsValid always return false in ASP.NET Core

I want to be able to upload an image to an entity called Game in my case. I use ModelView for the entity but every time I try to create a new object, I always end up with my ModelState being false.

Here's my Game Entity (it inherits Id property from the 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 connection with gameGenres
    public ICollection<GameGenres> GameGenres { get; set; }
    
    // to create connection with Reviews
    public ICollection<Review> Reviews { get; set; }
}

And here's my ModelView for it

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; }

And finally this is my post method for creating a new game in my controller:

[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);
}

When debugging, I also tried using Bind instead of [FromForm], but neither worked.

I have a folder creating in my root as well, but I have no idea why the ModelState.IsValid is always false.

Upvotes: 0

Views: 581

Answers (2)

Defcode
Defcode

Reputation: 1

Check to see if all of the models properties are defined to take null. This worked for me. example.

public string Name { get; set; }

to

public string? Name { get; set; }

Upvotes: 0

Kunal Samal
Kunal Samal

Reputation: 30

just give a break point on under the public action result,then run the code. when the code will hit the break point just keep the mouse pointer over the model state.There you will get 2 paremeters....1 is Keys n 2 is Value.Just Click on the value n check all the parameters....If any parameters returns value 1,then that parameter in the model is invalid.

Upvotes: 0

Related Questions