如何将 AJAX 请求中的 id 列表传递给 MVC 中的服务器

How to pass a list of id's in a AJAX request to the Server in MVC

在 MVC 中对服务器的 AJAX 请求中,如何将 ID 列表传递给控制器​​的操作函数?

无论是否使用 Html 助手,我都接受。

我知道 MVC 的模型绑定器在涉及 intstringbool.

等简单类型时没有问题

是不是像我必须在动作中使用 and array 来代替?

我不在乎是否必须使用 arrayList,即使字符串 intstrings 我也可以随时转换它们。我只需要在服务器上使用它们。 我的列表 ID 目前为 null。

Javascript:

var ids= [1,4,5];
// ajax request with ids..

MVC 操作:

public ActionResult ShowComputerPackageBuffer(List<int> ids) // ids are null
{
    // build model ect..
    return PartialView(model);
}

编辑: 添加了我的 AJAX 请求

$(document).ready(function () {
    $('#spanComputerPackagesBuffer').on('click', function () {
        var ids = $('#divComputerPackagesBuffer').data('buffer');
        console.log('bufferIds: ' + bufferIds);
        var data = {
            ids: ids
        };

        var url = getUrlShowComputerPackageBuffer();
        loadTable(url, "result", data);
    });
});

// AJAX's
function loadTable(url, updateTargetId, data) {
    var promise = $.ajax({
        url: url,
        dataType: "html",
        data: data
    })
    .done(function (result) {
        $('#' + updateTargetId).html(result);
    })
    .fail(function (jqXhr, textStatus, errorThrown) {
        var errMsg = textStatus.toUpperCase() + ": " + errorThrown + '. Could not load HTML.';
        alert(errMsg);
    });
};

// URL's
function getUrlShowComputerPackageBuffer() {
    return '@Url.Action("ShowComputerPackageBuffer", "Buffer")';
};

解决方案:// 感谢@aherrick 评论。我怀念过去的美好"traditional"

$.ajax({
    type: "POST",
    url: '@Url.Action("ShowComputerPackageBuffer", "Buffer")',
    dataType: "json",
    traditional: true,
    data: {
        bufferIds: bufferIds
    }
});

试试这个(我已经检查过了):

$(function () {
        var ids = [1, 4, 5];
        $.ajax({
            type: 'POST',
            contentType: 'application/json; charset=utf-8',
            url: '@Url.Action("YourAction", "YourController")',
            data: JSON.stringify( { ids: ids })
        }).done(function () {

        });
    });

您必须确保您的 contentTypeapplication/json 并且您的数据是字符串化的。

public ActionResult SaveSomething(int[] requestData) 
//or
public ActionResult SaveSomething(IEnumerable<int> requestData)

使用操作结果您无法收到 JSON 对象:

使用控制器:

[HttpPost]
    [Route( "api/Controller/SaveSomething" )]
    public object SaveTimeSheet( int[] requestData )
    {
        try
        {
            doSomethingWith( requestData );

            return new
            {
                status = "Ok",
                message = "Updated!"
            };
        }
        catch( Exception ex )
        {
            return new
            {
                status = "Error",
                message = ex.Message
            };
        }


}

java 脚本:

var ids = [1,4,5];
var baseUrl: 'localhost/yourwebsite'
$.ajax({
                    url: baseUrl + '/api/Controller/SaveSomething',
                    type: 'POST',
                    data: JSON.stringify(ids),
                    dataType: 'json',
                    contentType: 'application/json',
                    error: function (xhr) {
                        alert('Error: ' + xhr.statusText);
                    },
                    success: function (result) {
                        if (result != undefined) {
                            window.location.href = window.location.href;
                        }
                    },
                    async: false,
                });

使用traditional参数并将其设置为true

$.ajax({
    type: "POST",
    url: "/URL",
    dataType: "json",
    traditional: true,
    data: {}
});