2016-06-07 205 views
7

我想發佈一個空的javascript數組[]到webAPI並讓它創建一個空的整數列表。我也想要它,所以如果我發佈javascript null到webAPI,它將null指定給整數列表。發送空數組到webapi

JS:

var intArray = []; 
$.ajax({ 
    type: 'POST', 
    url: '/api/ListOfInts', 
    data: {'' : intArray}, 
    dataType: 'json' 
}); 

C#的WebAPI

[HttpPost] 
public void ListOfInts([FromBody]List<int> input) 

問題1)的Jquery拒絕發送數據{'' : []}視後的有效載荷。當我在陣列中添加的東西它的工作原理,如{'' : [1,2,3]}

問題2)Passing empty js array to controller gives null基於我閱讀,即使我得到它後空數組,則初始化列表爲空。討論的解決方案有這樣的清單總是初始化爲空,但我不想這樣。我希望它在某些情況下爲空(當發送null/undefined時),並且當發送[]時,它應該初始化爲空。

編輯:爲什麼我使用{'' : []}

+0

您是否嘗試過只發送數據:intArray? –

+0

是的,它根本不起作用。 WebAPI不知道如何處理它 – LearningJrDev

+0

在WebApi中,區分請求中的null和empty可能很困難。如果你正在使用這些在你的應用程序中設置某種「狀態」,我會重新思考你是如何做到的。可能發送某種標誌或某種東西,以便在服務器上正確初始化您的列表。 – jensendp

回答

21

使用JSON.stringify(intArray)contentType: 'application/json'作品對我來說:

$.ajax({ 
    url: "/api/values", 
    method: "POST", 
    contentType: 'application/json', 
    data: JSON.stringify([]) 
}); 

enter image description here

$.ajax({ 
    url: "/api/values", 
    method: "POST", 
    contentType: 'application/json', 
    data: null 
}); 

enter image description here

$.ajax({ 
     url: "/api/values", 
     method: "POST", 
     contentType: 'application/json', 
     data: JSON.stringify([1, 2, 3]) 
}); 

enter image description here

1

1.使用JSON.stringify()將JavaScript對象轉換爲JSON字符串。

2.使用contentType:'application/json',因爲它是JSON的正確MIME媒體類型。 What is the correct JSON content type?

數據類型是沒有必要的

數據:JSON.stringify(intArray), 的contentType: '應用/ JSON的'