有没有办法检测为什么 Ajax 调用没有到达 MVC 中的控制器?

Is there a way to detect why an Ajax call does not make it to a controller in MVC?

我试图在单击按钮时进行 AJAX 调用。我的程序应该向服务器发送请求以获取一些数据并将其显示在页面上。为了简单起见,我首先需要了解如何使 AJAX 调用起作用。我尝试了以下方法:

我在 ASP.Net MVC5 C# 中的控制器:

[HttpPost]
public string MyMethod(int somePara)
{
    return "it worked";
}

我的 AJAX 电话:

$("button#test").on("click", function() {
  $.ajax({
    type: "POST",
    url: loc + "/MyMethod",
    data: somePara = "",
    success: function(data) {
      alert(data);
    },
    error: function() {
      alert("Error")
    }
  });
});
<link href="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/css/bootstrap.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/3.4.1/js/bootstrap.min.js"></script>
<button class="btn btn-default btn-lg btn-block" id="test">
    <span class="glyphicon glyphicon-time"></span>
    Test
</button>

(AJAX 调用中的 loc 字段将定义我的控制器。)

当我在本地 运行 这段代码时,我的 AJAX 调用将 return 错误部分。

我应该改变什么?有什么方法可以检测到为什么会这样吗?

您请求的问题

  • 数据格式不正确somePara = "111" => JSON.stringify({ somePara: "111" }),

  • 没有定义数据类型

    内容类型:"application/json; charset=utf-8", 数据类型:"json",

  • 动作没有returnJSON格式。

控制器动作

  [HttpPost]
    public JsonResult MyMethod(int somePara)
    {
        return Json("it worked", JsonRequestBehavior.AllowGet);
    }

AJAX

 $("button#test").on("click", function () {


       $.ajax({
                    type: "POST",
                    url:  "/Home/MyMethod", // i try home controller
                    data: JSON.stringify({ somePara: "111" }),
                    contentType: "application/json; charset=utf-8",
                    dataType: "json",
                    success: function (data) {
                        alert(data);
                    },
                    error: function () {
                        alert("Error")
                    }
                });
            });

更新:操作应更改为 MyMethod(int? somePara) 以防止 somePara : "" 无法转换为 int。