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

如何使用 jQuery Ajax 正確地將物件陣列傳遞到 MVC 控制器?

Susan Sarandon
Susan Sarandon原創
2025-01-21 17:21:10979瀏覽

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

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

使用 jQuery 的 ajax() 方法將物件陣列傳送到 MVC 控制器時,控制器的參數可能會收到 null 值。本文概述了解決方案。

空值故障排除

問題通常源自於不正確的資料序列化和內容類型處理。 解決方法如下:

  1. 設定內容類型與資料類型:

    ajax() 函數需要明確的 contentTypedataType 設定:

    <code class="language-javascript">contentType: 'application/json; charset=utf-8',
    dataType: 'json',</code>
  2. JSON 序列化:

    物件陣列必須使用JSON.stringify()序列化為JSON格式。 像這樣建構資料:

    <code class="language-javascript">things = JSON.stringify({ things: things });</code>

說明性範例

此範例示範如何成功傳遞物件陣列:

<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 executed.');
        },
        error: function(response) {
            $('#result').html(response.responseText); // Display error details
        }
    });
});</code>

對應的控制器方法(C#範例):

<code class="language-csharp">public void PassThings(List<Thing> things)
{
    // Process the 'things' list here
}</code>

請記得將 /Home/PassThings 替換為您的實際控制器和操作。 使用 error 代替 failure 可以提供更多資訊的錯誤處理。 這種修改後的方法可確保正確的資料傳輸並防止null值問題。

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

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