You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Asp.net Core中jQuery POST数据绑定失败及导航属性赋值求助

ASP.NET Core 评论提交问题解决方案

问题1:为BlogComments填充外键BlogId及处理导航属性

  • 导航属性Blog无需前端传递:EF Core仅通过外键BlogId即可关联对应的BlogData记录,前端只需传递BlogId值。
  • 获取当前博客ID的两种方式:
    1. 隐藏域方式:在表单内添加隐藏域存储当前博客ID
      <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>
      
      在JS中读取并赋值:
      var blogId = $("#blogId").val();
      dataToPost.BlogId = blogId;
      
    2. 直接嵌入视图变量:在JS中直接使用视图模型的ID
      dataToPost.BlogId = @Model.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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.17 05:05:54