Asp.net Core中jQuery POST数据绑定失败及导航属性赋值求助
ASP.NET Core 评论提交问题解决方案
问题1:为BlogComments填充外键BlogId及处理导航属性
- 导航属性
Blog无需前端传递:EF Core仅通过外键BlogId即可关联对应的BlogData记录,前端只需传递BlogId值。 - 获取当前博客ID的两种方式:
- 隐藏域方式:在表单内添加隐藏域存储当前博客ID
在JS中读取并赋值:<form id="formPostComment"> <input type="hidden" id="blogId" value="@Model.Id" /> <!-- 其他表单输入项(name、email、message) --> <button id="btnPostComment" class="btn btn-main m-bottom-40">Post Comment</button> </form>var blogId = $("#blogId").val(); dataToPost.BlogId = blogId; - 直接嵌入视图变量:在JS中直接使用视图模型的ID
dataToPost.BlogId = @Model.Id;
- 隐藏域方式:在表单内添加隐藏域存储当前博客ID
问题2:解决后端参数绑定为null的问题
- 核心原因:前端以JSON格式提交数据,但ASP.NET Core默认不会从请求体自动绑定复杂类型参数,需添加
[FromBody]特性明确告知框架读取来源。 - 修改后端
PostComment方法:[HttpPost] public async Task<IActionResult> PostComment([FromBody] BlogComments blogComment) { if (blogComment != null && ModelState.IsValid) { await _context.BlogComments.AddAsync(blogComment); await _context.SaveChangesAsync(); } // 修正:通过BlogId(外键)获取对应博客,而非评论的Id var item = _mainBlogHelperModel.BlogDataItems.FirstOrDefault(x => x.Id == blogComment?.BlogId); return new JsonResult(new { comment = blogComment?.Comment, name = blogComment?.Name }); } - 额外优化:确保前端AJAX的
contentType: "application/json"保持不变,且dataToPost的属性名与BlogComments模型的属性名一致(如BlogId、Name等),避免大小写不匹配导致绑定失败。
内容的提问来源于stack exchange,提问作者nikhil
相关产品推荐
相关产品推荐

