ASP.NET Core下拉菜单选中ID获取异常:CompanyId传值始终为0
问题解决步骤
1. 定位核心问题
你当前视图绑定的是List<CompanyListVM>集合模型,但下拉框的name设为CompanyId,MVC模型绑定无法将单个字段值匹配到集合结构中,导致后端接收时只能拿到类型默认值(int默认0,string默认null)。
2. 推荐方案:改用复合视图模型
不要直接用集合作为视图模型,创建包含筛选参数、公司列表、管理人员列表的复合模型,让字段名和绑定结构匹配:
public class ManagerListViewModel { // 接收下拉选中的公司ID public int SelectedCompanyId { get; set; } // 渲染下拉框的公司列表 public List<CompanyListVM> Companies { get; set; } // 展示结果的管理人员列表 public List<ManagerVM> Managers { get; set; } } public class CompanyListVM { public int CompanyId { get; set; } public string CompanyName { get; set; } } public class ManagerVM { public int ManagerId { get; set; } public string ManagerName { get; set; } }
3. 修改视图代码
视图绑定到新的复合模型,下拉框的name对应SelectedCompanyId,确保绑定匹配:
@model ManagerListViewModel @using (Html.BeginForm("List", "YourController", FormMethod.Post)) { <div> @Html.DropDownListFor(m => m.SelectedCompanyId, new SelectList(Model.Companies, "CompanyId", "CompanyName"), "请选择公司") </div> <button type="submit">查询管理人员</button> @if (Model.Managers?.Any() == true) { <table> <thead> <tr> <th>管理人员ID</th> <th>姓名</th> </tr> </thead> <tbody> @foreach (var manager in Model.Managers) { <tr> <td>@manager.ManagerId</td> <td>@manager.ManagerName</td> </tr> } </tbody> </table> } }
4. 调整控制器方法
更新Get和Post方法,适配新的复合模型,同时保证Post后下拉框数据不丢失:
public class YourController : Controller { private readonly ICompanyService _companyService; private readonly IManagerService _managerService; public YourController(ICompanyService companyService, IManagerService managerService) { _companyService = companyService; _managerService = managerService; } [HttpGet] public IActionResult List() { var viewModel = new ManagerListViewModel { Companies = _companyService.GetAllCompanies(), Managers = new List<ManagerVM>() }; return View(viewModel); } [HttpPost] public IActionResult List(ManagerListViewModel model) { if (ModelState.IsValid) { model.Managers = _managerService.GetManagersByCompanyId(model.SelectedCompanyId); } // 重新赋值公司列表,防止Post后下拉框无数据 model.Companies = _companyService.GetAllCompanies(); return View(model); } }
5. 临时应急方案(不推荐长期使用)
如果暂时不想修改模型结构,可直接从Request.Form中手动获取值:
[HttpPost] public IActionResult List(List<CompanyListVM> model) { if (int.TryParse(Request.Form["CompanyId"], out int companyId)) { var managers = _managerService.GetManagersByCompanyId(companyId); // 后续渲染逻辑 } return View(model); }
此方法绕过模型绑定规范,不利于代码维护,仅作临时修复使用。
内容的提问来源于stack exchange,提问作者Dilara PINAR
相关产品推荐
相关产品推荐

