'ModelState.IsValid keeps being false because of SelectList in ASP.NET Core
I have a strange problem: a model that has a SelectList, but in POST action, ModelState.IsValid is false because of that SelectList:
public class CarMakesViewModel
{
public Guid Id { get; set; }
public Microsoft.AspNetCore.Mvc.Rendering.SelectList Nationalities { get; set; }
public Guid NationalityId { get; set; }
}
In Edit view:
<div class="form-group">
<label asp-for="NationalityId" class="form-label required"></label>
<select asp-for="NationalityId" name="NationalityId" asp-items="Model.Nationalities" class="form-control "></select>
<span asp-validation-for="NationalityId" class="text-danger form-control-sm"></span>
</div>
Controller:
[HttpPost]
public async Task<IActionResult> Edit(CarMakesViewModel model)
{
if (ModelState.IsValid)
{
//Edit Code
return RedirectToAction("Index");
}
await GetSelectList(model);
return View(model);
}
In the post, the Nationality SelectList is null and that is the usual but why Model.State.IsValid is always equal to false?
The error says:
Nationalities is required
And to be noted select option is rendered with text and values normally.
Solution 1:[1]
You probably using net 6. You can just make list nullable
public Microsoft.AspNetCore.Mvc.Rendering.SelectList? Nationalities { get; set; }
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Serge |
