You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

ASP.NET Core网站下拉框选择「No」值无法保存问题

问题分析与解决方案

问题现象

在ASP.NET Core 5应用中,多个页面的Yes/No下拉选择框出现异常:

  • 选择「Yes」提交后可正常保存到数据库,重载页面后下拉框能正确显示「Yes」
  • 选择「No」提交后无法保存,重载页面后下拉框对应位置为空
  • 测试将「No」改为「Not」后,该值可正常保存和显示
  • 改用普通输入框手动输入「No」可正常持久化并显示,问题仅出在下拉选择框上

代码示例

视图模型

public class PersonViewModel
{
    public string PersonId { get; set; }
    public string IsEmployed { get; set; }
    public List<SelectListItem> YesNoList { get; set; }
             = new List<SelectListItem>
                {
                    new SelectListItem("", "NA"),
                    new SelectListItem("Yes", "Yes"),
                    new SelectListItem("No", "No")
                };
}

视图代码

@model WFCDocuments.ViewModels.PersonViewModel
@{
    ViewData["Title"] = "Loan Processing Application";
    Layout = "/Views/Shared/_Layout.cshtml";
}

<div class="row">
    <div class="col-md-12">
        <div class="card border-1 rounded" style="margin: 20px 0px 20px 0px;">
            <div class="card-header">Borrower Information</div>
            <div class="card-body">

                <form id="personForm" asp-action="Borrower" asp-controller="Application" method="post">
                    <input type="hidden" asp-for="PersonId" />

                    <div class="form-group">
                        <label class="form-label">Are You Employed?<span style="color:red; font-weight:bold"> *</span></label>
                        <select asp-for="IsEmployed" asp-items="Model.YesNoList" class="form-select form-control-square">                            
                        </select>
                    </div>

                    <div class="form-group" style="margin-top:10px;">
                        <input type="submit" class="btn btn-outline-secondary btn-square" value="Save" />
                    </div>
                </form>
            </div>
        </div>
    </div>
</div>

表单无JavaScript交互

控制器GET方法

[HttpGet]
public async Task<IActionResult> Borrower()
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    PersonService personService = new PersonService();
    BorrowerPerson borrowerPerson = personService.GetPerson(user.PersonId, _unitOfWork);
    var person = _mapper.Map<PersonViewModel>(borrowerPerson);
    return View(person);
}

控制器POST方法

[HttpPost]
public async Task<IActionResult> Borrower(PersonViewModel model)
{
    var user = await _userManager.GetUserAsync(HttpContext.User);
    PersonService personService = new PersonService();
    BorrowerPerson person = personService.GetPerson(user.PersonId, _unitOfWork);
    person.IsEmployed = model.IsEmployed;
    var b = await _unitOfWork.BorrowerPeople.UpdateAsync(person);
    if (b == false)
    {
        return RedirectToAction("Borrower", "Application").WithWarning("", "Update Borrower Failed");
    }
    return RedirectToAction("Borrower", "Application").WithSuccess("", "Updated Borrower");
}

工作单元接口

namespace WFCDocuments.Domain.Interfaces
{
    public interface IUnitOfWork : IDisposable
    {
        IAddressRepository Addresses { get; }
        IApplicationAuditRepository ApplicationAudits { get; }
        IApplicationRepository Applications { get; }
        IBankruptcyRepository Bankruptcies { get; }
        ILoanFileRepository LoanFiles { get; }
        IBorrowerPersonRepository BorrowerPeople { get; }
        IDocumentAuditRepository DocumentAudits { get; }
        IDocumentRepository Documents { get; }
        IExpenseTypeRepository ExpenseTypes { get; }
        IFinancialAnalysisExpenseRepository FinancialAnalysisExpenses { get; }
        IFinancialAnalysisRepository FinancialAnalysis { get; }
        IHardshipRepository Hardships { get; }
        IHardshipTypeRepository HardshipTypes { get; }
        IPropertyRepository Properties { get; }
        INonEscrowedLoanRepository NonEscrowedLoans { get; }
        IRequiredIncomeDocumentationRepository RequiredIncomeDocumentations { get; }
        ILenderRepository Lenders { get; }
        IInvitedRepository Invited { get; }
        IStatusRepository Statuses { get; }
        IMenuRepository Menus { get; }
        IMessageRepository Messages { get; }
        IApplicationStatusRepository ApplicationStatuses { get; set; }
        ISignatureRepository Signatures { get; set; }
        IUserRepository Users { get; set; }
        INotificationRepository Notifications { get; set; }
        INotificationEventRepository NotificationEvents { get; set; }
        IIncomeDocumentRepository IncomeDocuments { get; set; }
        IEventLogRepository EventLogs { get; set; }
        ILoanFileNoteRepository LoanFileNotes { get; set; }
        int Complete();
    }
}

解决方案

这个问题大概率是模型绑定或HTML辅助器的值匹配异常,或是框架对特定字符串的隐性处理,可按以下步骤修复:

  1. 手动设置下拉框选中状态
    在GET方法映射ViewModel后,显式匹配并设置选中项,避免标签助手自动匹配出错:
var person = _mapper.Map<PersonViewModel>(borrowerPerson);
// 手动匹配选中项
if (!string.IsNullOrEmpty(person.IsEmployed))
{
    var targetItem = person.YesNoList.FirstOrDefault(item => item.Value.Equals(person.IsEmployed, StringComparison.OrdinalIgnoreCase));
    if (targetItem != null) targetItem.Selected = true;
}
return View(person);
  1. 修改下拉框值的格式
    将「No」对应的Value改为非可能触发特殊处理的字符串,比如「N」,同时保留显示文本为「No」:
new SelectListItem("No", "N")

同步调整数据库存储逻辑、ViewModel和实体类的赋值逻辑即可。

  1. 检查模型绑定与验证规则
    确认IsEmployed字段未添加[AllowedValues]等限制取值的验证特性,避免框架过滤「No」值。

  2. 直接获取表单值
    如果模型绑定仍失败,可在POST方法中直接从请求表单获取值:

var isEmployed = Request.Form["IsEmployed"];
person.IsEmployed = isEmployed;

内容的提问来源于stack exchange,提问作者Ryan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 13:10:35