使用 jQuery AJAX 將物件陣列傳送到 MVC 控制器
使用 jQuery 的 ajax()
方法將物件陣列傳送到 MVC 控制器時,一個常見問題是在控制器中接收陣列的 null
值。 即使控制器參數正確定義為 List<T>
.
解決方案涉及兩個關鍵調整:
指定 JSON 資料型別: ajax()
呼叫必須明確地將 contentType
和 dataType
設為 'application/json; charset=utf-8'
。
使用 JSON.stringify() 序列化資料: JavaScript 物件陣列需要使用 JSON.stringify()
轉換為 JSON 字串。 至關重要的是,這個字串應該將陣列封裝在屬性中(例如“things”)。
這是實作這些變更的修正程式碼:
<code class="language-javascript">$(document).ready(function () { const things = [ { id: 1, color: 'yellow' }, { id: 2, color: 'blue' }, { id: 3, color: 'red' } ]; const data = JSON.stringify({ things: things }); $.ajax({ contentType: 'application/json; charset=utf-8', dataType: 'json', type: 'POST', url: '/Home/PassThings', data: data, success: function () { $('#result').html('"PassThings()" successfully called.'); }, error: function (response) { $('#result').html(response.responseText); // Display error details } }); });</code>
以及對應的C#控制器方法:
<code class="language-csharp">public void PassThings(List<Thing> things) { // Access the 'things' array here } public class Thing { public int Id { get; set; } public string Color { get; set; } }</code>
透過執行這些步驟,您將透過 jQuery AJAX 成功將物件陣列傳輸到 MVC 控制器方法。 請注意 AJAX 呼叫中從 failure
到 error
的更改,以便更好地處理錯誤,顯示回應文字以進行偵錯。
以上是如何使用 jQuery AJAX 將物件陣列傳遞到 MVC 控制器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!