AngularJS向ASP.NET Core控制器POST数据时接收值为NULL的问题排查
我帮你梳理了代码里的几个关键问题,这些就是导致后端接收NULL的核心原因,一个个来修复:
1. 后端参数缺少[FromBody]特性
ASP.NET Core默认不会自动从请求体中绑定复杂类型参数,必须显式加上[FromBody]特性,否则控制器无法正确解析前端发送的JSON数据。修改你的StudentController代码:
[HttpPost] public JsonResult AddStudent([FromBody] Student stu) { if (stu != null) { db.Students.Add(stu); db.SaveChanges(); return Json(stu); } else { return Json("Some Error Occured"); } }
2. 请求URL不匹配
前端Service里的请求URL写的是'Employee/AddStudent/',但你的后端控制器是StudentController,正确的URL应该是'Student/AddStudent'(注意去掉末尾的斜杠,避免路由匹配问题)。修改Service.js中的AddEmp方法:
this.AddEmp = function (Employee) { var response = $http({ method: 'post', url: 'Student/AddStudent', // 修正URL data: Employee, // 无需手动JSON序列化,$http会自动处理 headers: { 'Content-Type': 'application/json' } // 明确指定请求头 }); console.log(Employee); return response; }
3. 前端字段映射完全混乱
这是最关键的问题!你的前端代码里字段绑定和对象构造完全错位了:
在
Controller.js的AddUpdateEmployee函数中,你构造的Employee对象字段和后端模型不匹配,还搞混了绑定值:// 错误的构造逻辑 var Employee = { Name: $scope.employeeName, Email: $scope.employeeAddress, // 把地址绑定到了Email字段 Age: $scope.employeeEmail // 把邮箱绑定到了Age字段 };从前端视图
Index.cshtml里的{{employee.StudentName}}、{{employee.StudnetAddress}}(注意这里还有拼写错误:Studnet→Student)、{{employee.StudentEmail}}可以看出,后端Student类的字段应该是StudentName、StudentAddress、StudentEmail、Age。先修正视图里的ng-model绑定错误:
<tr> <td><b>Email</b></td> <td> <input type="text" ng-model="employeeEmail" /> <!-- 修正为对应邮箱的模型 --> </td> </tr> <tr> <td><b>Age</b></td> <td> <input type="text" ng-model="employeeAge" /> <!-- 新增对应年龄的模型 --> </td> </tr>然后修正
Controller.js里的对象构造,确保和后端Student类字段完全匹配:var Employee = { StudentName: $scope.employeeName, StudentAddress: $scope.employeeAddress, StudentEmail: $scope.employeeEmail, Age: $scope.employeeAge };另外,视图里的
{{employee.StudnetAddress}}是拼写错误,要改成{{employee.StudentAddress}}。
4. 冗余的JSON序列化操作
你之前用了JSON.stringify(Employee),但Angular的$http服务会自动把JavaScript对象序列化为JSON,同时适配请求头,所以直接传data: Employee即可,不需要额外手动序列化。
把这些问题全部修复后,后端应该就能正确接收到前端发送的数据了。
内容的提问来源于stack exchange,提问作者Waqas Rauf

