ModelState.IsValid 由于 ASP.NET Core 中的 SelectList 而一直为假

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

我有一个奇怪的问题:模型有 SelectList,但在 POST 动作中,ModelState.IsValid 是错误的,因为 SelectList:

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

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

    public Guid NationalityId { get; set; }
}

在编辑视图中:

<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>

控制器:

[HttpPost]
public async Task<IActionResult> Edit(CarMakesViewModel model)
{
    if (ModelState.IsValid)
    {
       //Edit Code
       return RedirectToAction("Index");
    }

    await GetSelectList(model);

    return View(model);
}

post中,NationalitySelectList为null,这是通常的,但为什么Model.State.IsValid总是等于false

错误说:

Nationalities is required

需要注意的是 select 选项通常使用文本和值呈现。

您是否尝试应用 [ValidateNever] 属性来删除服务器端 Nationalities 的验证?

当应用于 属性 时,验证系统会排除 属性。

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

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

    public Guid NationalityId { get; set; }
}

您可能使用的是 net 6。您只需将列表设置为可为空即可

public Microsoft.AspNetCore.Mvc.Rendering.SelectList? Nationalities { get; set; }