从js向控制器发送一组int

时间:2013-05-10 12:05:31

标签: javascript jquery asp.net-mvc

内部视图我有相应复选框的图像列表。我想检查一下 图像或图像并将图像id存储到int数组。这个int数组应该发送给 控制器用于进一步处理。

我已经花了太多时间在这上面并且我在控制器上得到int []数据null

问题是: 为什么我在控制器上变为空?

解决! 在我的_Layout jquery脚本中,bundle调用是在文档的最后,当我移动到顶部时,一切正常。

查看

<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)
{
  ...
}

2 个答案:

答案 0 :(得分:2)

您可以将数组螺旋化并通过ajax发送。

Serializing to JSON in jQuery

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

答案 1 :(得分:0)

使用JSON.stringify

var myarr = [];
myarr[0] = 'as';
myarr[1] = 'we';

console.log ( JSON.stringify( myarr ) );

输出是:

["as","we"]

在PHP方面,使用json_decode

print_r( json_decode('["as","we"]') );

将输出:

Array ( [0] => as [1] => we ) 
相关问题