[SOLVED] ModelState.IsValid keeps being false because of SelectList in ASP.NET Core

Issue

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

Did you try to apply [ValidateNever] attribute to remove validate of the Nationalities on the server side?

When applied to a property, the validation system excludes that property.

public class CarMakesViewModel 
{
    public Guid Id { get; set; }

    [ValidateNever]
    public Microsoft.AspNetCore.Mvc.Rendering.SelectList Nationalities { get; set; }

    public Guid NationalityId { get; set; }
}

Answered By – Jackdaw

Answer Checked By – Robin (BugsFixing Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *