How to post an empty array (of ints) (jQuery -> MVC 3)

后端 未结 2 1740
自闭症患者
自闭症患者 2021-01-12 08:02

Using jQuery I am posting an array of int to my MVC 3 application by putting the array in the data parameter like so: data: { myIntArray: myIntArray }

2条回答
  •  栀梦
    栀梦 (楼主)
    2021-01-12 08:11

    You could do this:

    var myIntArray = new Array();
    
    // add elements or leave empty
    myIntArray.push(1);
    myIntArray.push(5);
    
    var data = myIntArray.length > 0 ? { myIntArray: myIntArray } : null;
    
    $.ajax({
        url: '@Url.Action("someAction")',
        type: 'POST',
        data: data,
        traditional: true,
        success: function (result) {
            console.log(result);
        }
    });
    

    or use a JSON request:

    var myIntArray = new Array();
    // add elements or leave empty
    myIntArray.push(1);
    myIntArray.push(5);
    
    $.ajax({
        url: '@Url.Action("someAction")',
        type: 'POST',
        data: JSON.stringify(myIntArray),
        contentType: 'application/json',
        success: function (result) {
            console.log(result);
        }
    });
    

提交回复
热议问题