skip to Main Content

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.

2

Answers


  1. 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; }
    }
    
    Login or Signup to reply.
  2. You probably using net 6. You can just make list nullable

    public Microsoft.AspNetCore.Mvc.Rendering.SelectList? Nationalities { get; set; }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search