javascript - 将 int 数组从 js 发送到 Controller

标签 javascript jquery asp.net-mvc

内部 View 我有带有相应复选框的图像列表。我想检查一下 一个或多个图像并将图像 ID 存储到 int 数组中。这个 int 数组应该被发送到 进一步处理的 Controller 。

我已经在这方面花费了太多时间,并且我在 Controller 上得到了 int[] 数据 null

问题是: 为什么我在 Controller 处得到 null?

已解决! 在我的 _Layout jquery 脚本中,捆绑调用位于文档的末尾,当我移动到顶部时,一切正常。

查看

<div id="newsImages">
    <img width="50" height="50" alt="" src="/imageOne.jpg">    
        <input type="checkbox" class="imgCheckbox" id="4">   
    <img width="50" height="50" alt="" src="/imageTwo.jpg">    
        <input type="checkbox" class="imgCheckbox" id="5">   
    <input type="button" value="Delete" name="deleteImgBtn" id="deleteImgBtn" class="deleteImagesBtn">    
</div>

JS

var imgList = [];
$(document).on("click", "#deleteImgBtn", function (e) {
    e.preventDefault();
    $('.imgCheckbox:checked').each(function () {        
        var id = $(this).attr('id');
        //add image id to the array of ints
        imgList.push(id);
    });
    jQuery.ajaxSettings.traditional = true;    
    var options = {
        url: '/news/deleteimages',
        type: 'POST',        
        data: { data: imgList },
        traditional: true
    };
    $.ajax(options).done(function (data) {
        var $target = $('#newsImages');
        $target.html(data);
    });
    //reset array of int to prevent browser to send duplicated 
    //img id to the controller on second attempt after ajax request is completed
    imgList.length = 0;
    //prevent browser from any default actions
    return false;
});

Controller

public ActionResult DeleteImages(int[] data)
{
  ...
}

最佳答案

您可以序列化数组并通过 ajax 发送它。

Serializing to JSON in jQuery

读取序列化数组,解析它..检查所有内容并继续

关于javascript - 将 int 数组从 js 发送到 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16481847/

相关文章:

javascript - 如何使用 Javascript 在 Adob​​e Illustrator 中调用 "symbol"?

javascript - 无法在表中添加动态行 - javascript

javascript - 为什么 Jquery 无法访问我页面上导入的元素

javascript - 如何在jquery ui进度条中使用变量

c# - 未经验证就发布

asp.net - 什么是 "Could not locate the assembly"错误?

c# - 如何让浏览器后退按钮通过 AJAX 调用带你返回?

javascript - 如何使用jquery替换html标签

javascript - 使用 jQuery 更新跨度内部 html .html 在 IE 中不起作用

javascript - 如何在react中显示来自api的数据