ASP.NET Core 6.0 MVC中Ajax传值Controller接收为null问题求助
问题解决建议
1. 修正JSON属性拼写错误
你实际发送的JSON数据存在两处属性名拼写错误,这是导致模型绑定失败的核心原因:
CandiateId→ 正确应为CandidateId(缺失字母d)ScreeninigId→ 正确应为ScreeningId(多了字母i)
ASP.NET Core的模型绑定要求属性名拼写完全匹配(大小写不敏感),错误的属性名会导致框架无法将JSON字段映射到ViewModel的属性,最终控制器接收值为null。
2. 控制器方法添加[FromBody]特性
在ASP.NET Core中,通过JSON格式传递复杂类型(如List<ScreeningViewModel>)时,必须显式指定从请求体读取数据,给控制器参数添加[FromBody]特性:
[HttpPost] public JsonResult SaveScreening([FromBody] List<ScreeningViewModel> lstScreeningViewModel) { // 业务逻辑 return Json(new { success = true, message = "Cambios guardados correctamente" }); }
3. 阻止表单默认提交行为
你的Ajax代码未阻止表单的默认提交动作,会导致页面刷新、Ajax请求被中断,需要在事件处理函数开头添加e.preventDefault();:
$("#frmScreeningProcess").on("submit", function (e) { e.preventDefault(); // 阻止表单默认提交 // 剩余代码... });
4. 优化JSON数据结构(可选)
当前Ajax代码将数组包裹在{ lstScreeningViewModel: ... }对象中,其实可以直接发送数组本身,结构更简洁且与控制器参数直接匹配:
data: JSON.stringify(lstScreeningViewModel),
修正后的完整Ajax脚本
$("#frmScreeningProcess").on("submit", function (e) { e.preventDefault(); var lstScreeningViewModel = []; var totalRows = $('#MustToHaveTable tr').length - 1; for (i = 0; i < totalRows; i++) { var candidateId = parseInt($("#ListCandidateScrViewModel_" + i + "__CandidateId").val()); var typeRequirement = $("#ListCandidateScrViewModel_" + i + "__TypeRequirement").val(); var screeningId = parseInt($("#ListCandidateScrViewModel_" + i + "__ScreeningId").val()); var selectedOption = $("#ListCandidateScrViewModel_" + i + "__SelectedOption").prop("checked"); lstScreeningViewModel.push({ CandidateId: candidateId, TypeRequirement: typeRequirement, ScreeningId: screeningId, SelectedOption: selectedOption }); }; $.ajax({ type: "POST", url: "/Candidate/SaveScreening", contentType: "application/json; charset=utf-8", dataType: "json", data: JSON.stringify(lstScreeningViewModel), success: function (response) { if (response.success) { console.log("Datos actualizados correctamente"); } else { alert("Error al guardar los cambios"); } }, error: function (xhr, status, error) { console.log("AJAX错误详情:", xhr.responseText); alert("Error en la solicitud AJAX"); } }); });
内容的提问来源于stack exchange,提问作者Luis Gerardo
相关产品推荐
相关产品推荐

