控制器返回List集合到前端视图时始终为null的问题求助
问题原因&解决方案
核心问题排查
- 异步执行顺序错误:
$.ajax是异步请求,你将console.log写在请求外侧时,请求还未完成返回,打印的是从表格行数据中取出的初始空值,而非后端返回数据 - 未配置请求回调:你的AJAX参数中没有添加
success回调函数,后端返回的结果没有被前端接收处理 - 后端返回类型不匹配:ASP.NET MVC/ASP.NET Core 控制器中直接返回
List<T>不会自动序列化为前端可识别的JSON格式,需要返回JsonResult类型 - 参数冗余:你同时在URL拼接和请求体中传递了
garageId,还传递了后端未接收的Values参数,属于无效配置
修正代码
1. C#后端代码修正
// 首先给接口添加HttpPost特性匹配前端请求类型 [HttpPost] public JsonResult getRequestType(int garageId) { List<GarageModel> newList = new List<GarageModel>(); // 注意:原有SQL拼接存在SQL注入风险,建议后续改为参数化查询优化 string sql = "SELECT GarageID, RequestProperty FROM GarageCrossRequestType WHERE GarageID = " + garageId; var cmd = new SqlCommand(sql, Connection); var dt = new DataTable(); dt.Load(cmd.ExecuteReader()); foreach (DataRow i in dt.Rows) { var model = new GarageModel(); model.GarageId = Convert.ToInt32(i["GarageID"].ToString()); model.Values = Convert.ToInt32(i["RequestProperty"].ToString()); newList.Add(model); } // 将结果用Json方法序列化后返回 return Json(newList); }
2. 前端JS代码修正
function editGarage(e) { e.preventDefault(); var dataItem = this.dataItem($(e.currentTarget).closest("tr")); var garageId = dataItem.GarageId; countryId = dataItem.CountryId; name = dataItem.Name; customerNumberOfEditingGarage = dataItem.CustomerNumber; $.ajax({ type: 'POST', url: '@Url.Action("getRequestType", "Garage")', dataType: 'JSON', // 只传必要的参数 data: { garageId: garageId }, // 成功回调:请求正常返回后触发 success: function(res) { // res就是后端返回的GarageModel数组 console.log("返回的完整列表数据:", res); // 打印对应garageId和返回的Values示例 if(res.length > 0) { console.log("garageId:", garageId, "Values:", res[0].Values); } }, // 错误回调:请求失败时打印错误信息方便排查 error: function(err) { console.log("请求异常:", err); } }); }
额外优化建议
原有SQL语句采用字符串拼接方式传参,存在SQL注入风险,建议修改为参数化查询实现,示例如下:
string sql = "SELECT GarageID, RequestProperty FROM GarageCrossRequestType WHERE GarageID = @GarageId"; var cmd = new SqlCommand(sql, Connection); cmd.Parameters.AddWithValue("@GarageId", garageId);
内容的提问来源于stack exchange,提问作者BravaDejana
相关产品推荐
相关产品推荐

