簡體   English   中英

使用Ajax調用控制器方法

[英]Call the controller method using 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; }
}

我認為有2點需要解決:

  1. 沒有類型的ajax將成為GET請求。 張貼POST
  2. 嘗試使用數據: JSON.stringify({ 'pDetail': billArray})

因此,它變為:

$.ajax({
    url: "/Cashier/UpdateProductQuantity",
    type : 'POST',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    data: JSON.stringify({ 'pDetail': billArray}),
    responseType: "json",
    success: function (data) {
        alert('success');
    }
});

我會嘗試使用FromBody與您的控制器:

[HttpPost]
public JsonResult UpdateProductQuantity([FromBody]List<Test> pDetail)
{
    return Json("", JsonRequestBehavior.AllowGet);
}

您說您需要發布billArray,因此您的ajax請求應該是這樣的發布類型:

$.ajax({
url: "/Cashier/UpdateProductQuantity",
type : 'POST', //this is the difference
contentType: "application/json; charset=utf-8",
dataType: "json",
data: JSON.stringify({ 'pDetail': billArray}),
responseType: "json",
success: function (data) {
    alert('success');
}
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM