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
Did you try to apply
[ValidateNever]
attribute to remove validate of theNationalities
on the server side?When applied to a property, the validation system excludes that property.
You probably using net 6. You can just make list nullable