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

如何在ASP.NET Core中实现JavaScript数据传递至Controller?

问题排查与解决方案

1. Ajax请求配置错误

你的Ajax设置了processData: false,这个选项会阻止jQuery将请求数据编码为表单格式(application/x-www-form-urlencoded),导致ASP.NET Core无法正确解析参数,这是触发500错误的核心原因之一。

修复方案:
移除processData: false(默认值为true,会自动处理数据格式),或者显式设置为true。同时确保请求的contentType正确(默认即可,无需额外设置)。

修改后的addMoveToDB函数:

function addMoveToDB(id, mrow, mcol)
{
  $.ajax({
      url: '/GamePiece/GameBoard',
      type: 'POST',
      async: true,
      data: { 
          id: id, 
          mrow: mrow,
          mcol: mcol
      },
      success: function (data) {alert("success");},
      error: function (jqXHR, exception) {
          var msg = '';
          if (jqXHR.status === 0) {
              msg = 'Not connect.\n Verify Network.';
          } else if (jqXHR.status == 404) {
              msg = 'Requested page not found. [404]';
          } else if (jqXHR.status == 500) {
              msg = 'Internal Server Error [500].\n' + jqXHR.responseText;
          } else if (exception === 'parsererror') {
              msg = 'Requested JSON parse failed.';
          } else if (exception === 'timeout') {
              msg = 'Time out error.';
          } else if (exception === 'abort') {
              msg = 'Ajax request aborted.';
          } else {
              msg = 'Uncaught Error.\n' + jqXHR.responseText;
          }
          $('#post').html(msg);
      },
  });
}

2. 缺少CSRF防伪造令牌验证

ASP.NET Core默认要求POST请求携带CSRF令牌,否则会拒绝请求(可能触发500或400错误)。需要在Ajax请求中添加该令牌。

修复方案:
在视图中添加隐藏的CSRF令牌,然后在Ajax请求中带上该令牌。

步骤1:在视图的页面中添加令牌:

@Html.AntiForgeryToken()

步骤2:修改Ajax请求,添加headers携带令牌:

function addMoveToDB(id, mrow, mcol)
{
  // 获取CSRF令牌
  var token = $('input[name="__RequestVerificationToken"]').val();
  
  $.ajax({
      url: '/GamePiece/GameBoard',
      type: 'POST',
      async: true,
      headers: {
          'RequestVerificationToken': token
      },
      data: { 
          id: id, 
          mrow: mrow,
          mcol: mcol
      },
      // 其余代码不变
  });
}

同时,确保Controller的Action上添加[ValidateAntiForgeryToken]特性:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> GameBoard(string id, string mrow, string mcol)
{
    // 原有代码
}

3. 前端DOM操作语法错误

selectPiece函数中设置背景色的代码有误:

gamePiece.style.backgroundColor("lightblue");

正确的语法应该是赋值,不是函数调用:

gamePiece.style.backgroundColor = "lightblue";

4. Controller异常处理与参数验证优化

当前Controller的try-catch块直接抛出异常,无法定位具体错误(比如Guid.Parse(id)失败、int.Parse(mrow/mcol)失败),建议添加详细的异常捕获和参数验证,返回友好的错误信息。

优化后的Controller代码:

[HttpPost]
[ValidateAntiForgeryToken]
public async Task<ActionResult> GameBoard(string id, string mrow, string mcol)
{
    try
    {
        // 参数验证
        if (string.IsNullOrEmpty(id) || !Guid.TryParse(id, out Guid gamePieceId))
        {
            return BadRequest("无效的游戏棋子ID");
        }
        if (!int.TryParse(mrow, out int row) || !int.TryParse(mcol, out int col))
        {
            return BadRequest("无效的行列参数");
        }

        GameVM gameVM = new GameVM();
        GamePiece gamePiece = await GamePieceManager.LoadById(gamePieceId);
        
        if (gamePiece == null)
        {
            return NotFound("未找到指定的游戏棋子");
        }

        gamePiece.Row = row;
        gamePiece.Col = col;
        await GamePieceManager.Update(gamePiece);
        gameVM.gamePieces = await GamePieceManager.LoadByGameId(gamePiece.GameId);
        
        return PartialView(gameVM);
    }
    catch (Exception ex)
    {
        return StatusCode(500, $"服务器内部错误:{ex.Message}");
    }
}

5. 调试建议

  • 打开浏览器开发者工具(F12),查看Network标签下的POST请求,检查请求参数是否正确发送,响应内容是否有详细错误信息。
  • 在Controller的Action中添加断点,调试参数是否正确接收。

内容的提问来源于stack exchange,提问作者VueLegend

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 07:25:24