如何将 AJAX 请求中的 id 列表传递给 MVC 中的服务器 [英] How to pass a list of id's in a AJAX request to the Server in MVC

查看:40
本文介绍了如何将 AJAX 请求中的 id 列表传递给 MVC 中的服务器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

I accept with or without use of Html helpers.

我知道 MVC 的模型绑定器在处理 intstringbool 等简单类型时没有问题.

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

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

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

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

I don't care if I have to use an array or List and even if the strings I int or strings I can always convert them. I just need them on the server. My List ids gives null at the moment.

Javascript:

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 请求

Added my AJAX request

$(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 评论.我想念旧的传统"

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

推荐答案

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

Use the traditional parameter and set it to true.

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

这篇关于如何将 AJAX 请求中的 id 列表传递给 MVC 中的服务器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆