jQuery Ajax を使用してオブジェクトのリストを MVC コントローラー メソッドに渡す 質問する

jQuery Ajax を使用してオブジェクトのリストを MVC コントローラー メソッドに渡す 質問する

jQuery の ajax() 関数を使用して、オブジェクトの配列を MVC コントローラー メソッドに渡そうとしています。 PassThing() C# コントローラー メソッドに入ると、引数 "things" が null になります。引数に List 型を使用してこれを試しましたが、それでもうまくいきません。何が間違っているのでしょうか?

<script type="text/javascript">
    $(document).ready(function () {
        var things = [
            { id: 1, color: 'yellow' },
            { id: 2, color: 'blue' },
            { id: 3, color: 'red' }
        ];

        $.ajax({
            contentType: 'application/json; charset=utf-8',
            dataType: 'json',
            type: 'POST',
            url: '/Xhr/ThingController/PassThing',
            data: JSON.stringify(things)
        });
    });
</script>

public class ThingController : Controller
{
    public void PassThing(Thing[] things)
    {
        // do stuff with things here...
    }

    public class Thing
    {
        public int id { get; set; }
        public string color { get; set; }
    }
}

ベストアンサー1

NickW の提案を使用して、これを動作させることができましたthings = JSON.stringify({ 'things': things });。完全なコードは次のとおりです。

$(document).ready(function () {
    var things = [
        { id: 1, color: 'yellow' },
        { id: 2, color: 'blue' },
        { id: 3, color: 'red' }
    ];      
    
    things = JSON.stringify({ 'things': things });

    $.ajax({
        contentType: 'application/json; charset=utf-8',
        dataType: 'json',
        type: 'POST',
        url: '/Home/PassThings',
        data: things,
        success: function () {          
            $('#result').html('"PassThings()" successfully called.');
        },
        failure: function (response) {          
            $('#result').html(response);
        }
    }); 
});


public void PassThings(List<Thing> things)
{
    var t = things;
}

public class Thing
{
    public int Id { get; set; }
    public string Color { get; set; }
}

このことから私が学んだことは 2 つあります。

  1. contentType と dataType の設定は、ajax() 関数では絶対に必要です。これらが欠落していると機能しません。私は何度も試行錯誤した結果、このことに気付きました。

  2. MVC コントローラー メソッドにオブジェクトの配列を渡すには、JSON.stringify({ 'things': things }) 形式を使用するだけです。

おすすめ記事