首頁 >後端開發 >C++ >如何使用 jQuery AJAX 將物件陣列傳遞到 MVC 控制器?

如何使用 jQuery AJAX 將物件陣列傳遞到 MVC 控制器?

Patricia Arquette
Patricia Arquette原創
2025-01-21 17:17:14857瀏覽

How to Pass an Array of Objects to an MVC Controller Using jQuery AJAX?

使用 jQuery AJAX 將物件陣列傳送到 MVC 控制器

使用 jQuery 的 ajax() 方法將物件陣列傳送到 MVC 控制器時,一個常見問題是在控制器中接收陣列的 null 值。 即使控制器參數正確定義為 List<T>.

,也可能發生這種情況

解決方案涉及兩個關鍵調整:

  1. 指定 JSON 資料型別: ajax() 呼叫必須明確地將 contentTypedataType 設為 'application/json; charset=utf-8'

  2. 使用 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 呼叫中從 failureerror 的更改,以便更好地處理錯誤,顯示回應文字以進行偵錯。

以上是如何使用 jQuery AJAX 將物件陣列傳遞到 MVC 控制器?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn