将POST发送到控制器方法c#+ ajax

时间:2015-01-06 14:11:44

标签: c# jquery ajax asp.net-mvc

有这个js ajax方法:

$.ajax({
  type: "POST",
  url: "/Mycontroller/MyMethod",
  data: { Id: '1' },
  success: function (data) {
  if (data.IsSuccess == true) {
      console.log('All OK!');
      }
  }
});

我控制器中的这个方法:

[HttpPost]
public  ActionResult MyMethod(int Id)
{
  ....
  return Json(new { IsSuccess = true}
}

但是,当我在visual studio中使用调试器时,他不会让我转到“console.log'代码。

我无法理解为什么代码无效。

P.S。按下按钮时脚本工作

1 个答案:

答案 0 :(得分:1)

试试这个:

$.ajax({
        url: 'PUT_YOUR_URL_HERE',
        dataType: "json",
        type: "POST",
        contentType: 'application/json; charset=utf-8',
        data: JSON.stringify({ Id: 1 }),
        async: true, // Or false           
        cache: false,
        success: function (data) {
           //do something
            }

        },
        error: function (xhr) {
            alert('error');
        }
    })
  • 如果我没错 - MyMethod(int Id) - 此ID - GET Parameter

如果您需要发送为POST - 请写如下:

MyMethod()
{
int id = Convert.ToInt32(Request["Id"]);
}