0

Inside view I have list of images with corresponding checkboxes. I want to check image or images and store image id's to int array. This int array should be sent to the controller for further process.

I'm already spend too much time on this and I'm getting int[] data null at controller

Question is: Why I'm getting null at controller?

SOLVED! In my _Layout jquery scripts bundle call was at the end of the document, when I was move to the top everything works.

View

<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)
{
  ...
}
user1765862
  • 13,635
  • 28
  • 115
  • 220
  • You are trying to passing a js array. Just try a js object instead. Also you can try: - make the array json and set the ajax property datatype: json – Kiren S May 10 '13 at 12:12

2 Answers2

2

You can seralize your array and send it via ajax.

Serializing to JSON in jQuery

and read the seriazlized array, parse it..check every thing and go

Community
  • 1
  • 1
0

Use JSON.stringify.

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

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

Output is:

["as","we"]

On your PHP side, use json_decode:

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

will output:

Array ( [0] => as [1] => we ) 
RRikesh
  • 14,112
  • 5
  • 49
  • 70