MVC项目点击表格行显示评论时出现undefined问题求助
MVC + EF Core 评论显示
undefined问题排查修复 问题描述
基于MVC模板和Entity Framework Core开发的应用,核心功能为:从数据库读取企业数据展示在HTML表格中,点击表格内企业行时,右侧展示该企业的评论。实际操作时,右侧未显示评论内容,而是出现undefined。例如测试企业的两条评论"Comment test 1"、"Comment test 2",均显示为undefined。
相关代码
评论展示脚本
@section scripts { <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(function () { var selectedCompanyId = $("tbody tr:first").data("company-id"); $("tbody tr:first").addClass("selected"); $("tbody tr").on("click", function () { $("tbody tr").removeClass("selected"); $(this).addClass("selected"); var companyId = $(this).data("company-id"); $.get("/Home/GetComments", { companyId: companyId }, function (data) { var commentsHtml = ""; data.forEach(function (comment) { commentsHtml += "<div>" + comment.Content + "</div>"; }); $("#company-comments").html(commentsHtml); }); }); }); </script> }
HomeController.cs
public class HomeController : Controller { private readonly CompanyDataContext context; public HomeController(CompanyDataContext context) { this.context = context; } public IActionResult Index() { var companies = this.context.Companies .Select(c => new CompanyViewModel { CompanyId = c.CompanyId, Name = c.Name, Count = c.Comments.Count, Comments = c.Comments.Select(co => new CommentViewModel { CommentCompanyId = co.CompanyId, CommentId = co.CommentId, Content = co.Content }).ToList() }).ToList(); return View(companies); } [HttpGet] public List<Comment> GetAll() { return context.Comments.ToList(); } public async Task<IActionResult> GetComments(int companyId) { var company = await this.context.Companies .Include(c => c.Comments) .FirstOrDefaultAsync(c => c.CompanyId == companyId); if (company == null) { return NotFound(); } var comments = company.Comments.Select(c => new CommentViewModel { CommentCompanyId = c.CompanyId, CommentId = c.CommentId, Content = c.Content }); return Ok(comments); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } }
Index.cshtml
@model IEnumerable<CompanyApp.ViewModels.CompanyViewModel> @{ ViewData["Title"] = "Home Page"; } <div style="display: flex;" class=" container"> <div class="box1"> <table id="my-table" class="my-table"> <thead> <tr> <th>Company ID</th> <th>Company Name</th> <th>Comments</th> </tr> </thead> <tbody> @foreach (var company in Model) { <tr data-company-id="@company.CompanyId"> <td>@company.CompanyId</td> <td>@company.Name</td> <td align="center">@company.Count</td> </tr> } </tbody> </table> </div> <div id="company-comments" class="box2"></div> </div> @section scripts { <script src="https://code.jquery.com/jquery-3.6.0.min.js"></script> <script> $(function () { var selectedCompanyId = $("tbody tr:first").data("company-id"); $("tbody tr:first").addClass("selected"); $("tbody tr").on("click", function () { $("tbody tr").removeClass("selected"); $(this).addClass("selected"); var companyId = $(this).data("company-id"); $.get("/Home/GetComments", { companyId: companyId }, function (data) { var commentsHtml = ""; data.forEach(function (comment) { commentsHtml += "<div>" + comment.Content + "</div>"; }); $("#company-comments").html(commentsHtml); }); }); }); </script> }
问题原因及修复方案
核心原因
ASP.NET Core默认会将JSON序列化的属性名转换为驼峰命名,后端CommentViewModel的Content属性会被序列化为content,但前端JS中仍用comment.Content访问,导致取不到值,返回undefined。此外,Index.cshtml中重复定义了@section scripts,会引发脚本重复加载问题。
修复步骤
方案1:前端适配驼峰命名
修改JS中访问属性的代码,将comment.Content改为comment.content:
data.forEach(function (comment) { commentsHtml += "<div>" + comment.content + "</div>"; });
方案2:后端保持原属性名序列化
在Program.cs中配置JSON序列化保留大驼峰属性名:
builder.Services.AddControllersWithViews() .AddJsonOptions(options => { options.JsonSerializerOptions.PropertyNamingPolicy = null; });
额外修复:合并重复脚本块
删除Index.cshtml中重复的@section scripts,只保留一个脚本块,避免重复加载jQuery和逻辑代码。
可选优化:初始化加载第一条评论
页面加载后主动加载第一行企业的评论,完善用户体验:
$(function () { var selectedRow = $("tbody tr:first"); var selectedCompanyId = selectedRow.data("company-id"); selectedRow.addClass("selected"); // 初始化加载第一条评论 loadComments(selectedCompanyId); $("tbody tr").on("click", function () { $("tbody tr").removeClass("selected"); $(this).addClass("selected"); var companyId = $(this).data("company-id"); loadComments(companyId); }); // 提取加载逻辑为函数 function loadComments(companyId) { $.get("/Home/GetComments", { companyId: companyId }, function (data) { var commentsHtml = ""; data.forEach(function (comment) { commentsHtml += "<div>" + comment.content + "</div>"; }); $("#company-comments").html(commentsHtml); }); } });
内容的提问来源于stack exchange,提问作者zeddrus
相关产品推荐
相关产品推荐

