Home > Back-end >  ModelState.IsValid keeps being false because of SelectList in ASP.NET Core
ModelState.IsValid keeps being false because of SelectList in ASP.NET Core

Time:02-19

I have a strange problem: I have 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 >
    <label asp-for="NationalityId" ></label>
    <select asp-for="NationalityId" name="NationalityId" asp-items="Model.Nationalities" ></select>
    <span asp-validation-for="NationalityId" ></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

CodePudding user response:

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

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

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

    public Guid NationalityId { get; set; }
}
  • Related