Search code examples
c#entity-frameworkasp.net-coremodel-view-controllermodel-binding

ModelState doesn't see value


In my controller, I want to update FileContent in Image model. But ModelState says it's null.

[HttpPost]
public async Task<IActionResult> AddImage([Bind("Id,Title,ImageFile, TradeId")] Image image)
{
    // Sprawdź, czy plik został przesłany
    if (image.ImageFile != null && image.ImageFile.Length > 0)
    {
        using var ms = new MemoryStream();
        await image.ImageFile.CopyToAsync(ms);
        byte[] fileBytes = ms.ToArray();
        image.FileContent = Convert.ToBase64String(fileBytes);
    }
    else
    {
        ModelState.AddModelError("ImageFile", "Image file is required.");
        return View(image); // Ponownie wyświetl formularz z błędem
    }

    if (ModelState.IsValid)
    {
        // insert record
        _context.Add(image);
        await _context.SaveChangesAsync();
        return RedirectToAction("Details", "Trades", new {id = image.TradeId});
    }
    return View(image);
}

The problem is, this value isn;t null in debugger Debbuger

What do I have to do to pass ModelState validation ? I want the image to be added as base64


Solution

  • I can reproduce your issue in my side. Please see screenshot below. Before we set value to Image.FileContent, the model validation task already completed and we can see it's false.

    enter image description here

    Let's take a look at the model validation document. It says

    Both model binding and model validation occur before the execution of a controller action or a Razor Pages handler method.

    So that we have to make sure the FileContent property is nullable, or in the post request, we give this property value. Since .Net 6, we will have <Nullable>enable</Nullable> in the cspro file so that in our model, even if we don't give it a [Required] attribute, it will be non-nullable by default. This caused my invalid error. The solution is make this property to be nullable, which requires us to use public string? FileContent { get; set; }.

    enter image description here