ASP.NET Razor中jQuery Ajax追加Json数据到HTML表格的问题
问题解决:ASP.NET Razor中Ajax刷新表格数据异常
问题根源分析
- 遍历对象而非数组:
RefreshDataTable接口返回的是单个用户对象,但前端错误使用$.each遍历,会把对象的每个键值对拆分为独立item,导致无法读取CompanyName这类对象属性,触发报错或undefined。 - 属性名大小写不匹配:接口返回的JSON采用小驼峰命名(如
companyName、branchName),但前端代码用的是大驼峰(CompanyName、BranchName),JS对大小写敏感,因此读取不到对应属性值,显示undefined。
修正步骤
1. 前端Ajax代码修正
直接处理单个返回对象,同时修正属性名大小写,补全Actions列的Edit按钮:
$("#updatedatabtn").click(function () { var userId = $("#userId").val(); $.ajax({ url: '?handler=RefreshDataTable', dataType: 'json', data: { UserId: userId }, success: function (result) { console.log(result); $("#myDataTable tbody").empty(); // 直接拼接单个用户行,无需遍历 var row = `<tr> <td>${result.companyName || ''}</td> <td>${result.branchName || ''}</td> <td>${result.userName || ''}</td> <td>${result.userType || ''}</td> <td> <button class="btn btn-primary edit-btn" style="width:100px;" data-id="${result.id}">Edit</button> </td> </tr>`; $("#myDataTable tbody").append(row); }, error: function (xhr, status, error) { console.error("AJAX请求失败: " + error); } }); });
2. 后端代码优化(可选)
如果后续需要支持批量用户数据返回,可修改后端返回数组格式,兼容批量场景:
[BindProperty] public UserDto MyData { get; set; } public JsonResult OnGetRefreshDataTable(string UserId) { var result = userService.GetUserDetails(UserId.ToString()); if (result.Result == null) { return new JsonResult(new { Message = "未找到用户数据" }); } MyData = result.Result; // 返回包含单个对象的数组,兼容批量逻辑 return new JsonResult(new List<UserDto> { MyData }); }
若改为数组返回,前端可恢复$.each遍历,仍需注意属性名大小写:
$.each(result, function (index, item) { var row = `<tr> <td>${item.companyName || ''}</td> <td>${item.branchName || ''}</td> <td>${item.userName || ''}</td> <td>${item.userType || ''}</td> <td> <button class="btn btn-primary edit-btn" style="width:100px;" data-id="${item.id}">Edit</button> </td> </tr>`; $("#myDataTable tbody").append(row); });
3. 空值防护补充
在后端添加空值判断,避免返回null导致前端报错;前端也可通过|| ''处理空值,保证表格显示正常。
内容的提问来源于stack exchange,提问作者ahmed abdelaziz
相关产品推荐
相关产品推荐

