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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/28855763/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 02:30:24  来源:igfitidea点击:

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

javascriptajaxasp.net-mvcasp.net-mvc-4asp.net-mvc-5

提问by radbyx

In a AJAX request to the server in MVC, how can I pass a list of id's to the controller's action function?

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

I accept with or without use of Html helpers.

我接受使用或不使用 Html 助手。

I know MVC's model binder has no problem when it comes to simple types like int, stringand bool.

我知道 MVC 的模型绑定器在处理int,string和等简单类型时没有问题bool

Is it something like I have to use and array instead in the action?

是不是我必须在动作中使用和数组来代替?

I don't care if I have to use an arrayor Listand even if the strings I intor stringsI can always convert them. I just need them on the server. My List ids gives null at the moment.

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

Javascript:

Javascript:

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

MVC Action:

MVC 动作:

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

EDIT:Added my AJAX request

编辑:添加了我的 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")';
};

SOLUTIONS: // Thanks to @aherrick comment. I missed the good old "traditional"

解决方案:// 感谢@aherrick 评论。我错过了古老的“传统”

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

回答by aherrick

Use the traditionalparameter and set it to true.

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

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

回答by MacGyver

Try this one (I've checked it):

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

$(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 () {

        });
    });

You have to make sure your contentTypeis application/jsonand your data is stringified.

你必须确保你的contentType就是application/json你的数据字符串化。

回答by SilentTremor

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

Using Action Result you cannot receive JSON object:

使用 Action Result 您无法接收 JSON 对象:

Using Controler:

使用控制器:

[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 script:

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,
                });