使用 Ajax 调用控制器方法

我正在尝试使用 ajax 调用控制器的方法,但不知何故我无法调用该方法。我正在发送一个数组类型对象作为要发布的参数,但没有在控制器上获取参数的值,即使我发送了参数,JSON.stringify但问题仍然存在。


这是我的ajax方法。


$('.btn-generate-bill').on('click', function(event) {

  event.preventDefault();

  const billArray = [];

  $('.posTable').find('tbody tr').each(function(index, elem) {

    billArray.push({

      ProductID: $(elem).find('.productID').text().trim(),

      Quantity: $(elem).find('.qtyControl').val()

    });

  })

  console.log(JSON.stringify(billArray));

  $.ajax({

    url: "/Cashier/UpdateProductQuantity",

    contentType: "application/json; charset=utf-8",

    dataType: "json",

    data: {

      pDetail: JSON.stringify(billArray)

    },

    responseType: "json",

    cache: false,

    traditional: true,

    async: false,

    processData: true,

    success: function(data) {

      alert('success');

    }

  });

})

这是控制器的方法。


public JsonResult UpdateProductQuantity(List<Test> pDetail)

{

    return Json("", JsonRequestBehavior.AllowGet);

}


public class Test

{

    public int ProductID { get; set; }

    public int Quantity { get; set; }

}


慕田峪4524236
浏览 378回答 2
2回答

ITMISS

我认为有两点需要解决:没有类型的ajax将成为GET请求。放POST尝试使用数据:&nbsp;JSON.stringify({ 'pDetail': billArray})所以,它变成:$.ajax({&nbsp; &nbsp; url: "/Cashier/UpdateProductQuantity",&nbsp; &nbsp; type : 'POST',&nbsp; &nbsp; contentType: "application/json; charset=utf-8",&nbsp; &nbsp; dataType: "json",&nbsp; &nbsp; data: JSON.stringify({ 'pDetail': billArray}),&nbsp; &nbsp; responseType: "json",&nbsp; &nbsp; success: function (data) {&nbsp; &nbsp; &nbsp; &nbsp; alert('success');&nbsp; &nbsp; }});

千万里不及你

我会用你的控制器尝试 FromBody:[HttpPost]public JsonResult UpdateProductQuantity([FromBody]List<Test> pDetail){&nbsp; &nbsp; return Json("", JsonRequestBehavior.AllowGet);}你说你需要发布你的 billArray 所以你的 ajax 请求应该是这样的发布类型:$.ajax({url: "/Cashier/UpdateProductQuantity",type : 'POST', //this is the differencecontentType: "application/json; charset=utf-8",dataType: "json",data: JSON.stringify({ 'pDetail': billArray}),responseType: "json",success: function (data) {&nbsp; &nbsp; alert('success');}});
打开App,查看更多内容
随时随地看视频慕课网APP