user6208218
user6208218

Reputation:

Pass an array as parameter to a controller from an ajax call in JavaScript

I'm working on an ASP.NET MVC 4 website and I've got some troubles with a functionality. I explain, I've to select entities displayed in a table with their linked checkbox :

Screenshot of my table where each row has a checkbox with the same Id as the entity

Console showing updates in the array

Inside my script I have been abled to store each checked Id's checkbox in an array and remove those if the checkbox is unchecked. But I can't pass the array to my controller's function to delete each selected entity in the database. I used $.ajax() from jquery to send through a POST request the array (as JSON) but I always get 500 error :

Here's my function in my script (I don't know if my array's format is valid) :

    var sendDocsToDelete = function (docsArray) {
        $.ajax({
            type: 'POST',
            url: 'Main/DeleteDocuments',
            data: JSON.stringify(docsArray),
            contentType: 'application/json; charset=utf-8',
            datatype: 'json',
            success: function (result) {
                alert('Success ' + result.d);
            },
            error: function (result) {
                alert('Fail ' + result.d);
            }
        });
    }

Then, the POST call the following function in my controller :

    [Authorize]
    [WebMethod]
    public void DeleteDocuments(string docsToDelete)
    {
        int id; 
        string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);

        foreach (string docId in arrayDocs)
        {
            int.TryParse(docId, out id);
            dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
        }
    }

Update 2

    [Authorize]
    public ActionResult DeleteDocuments(int[] docsToDelete)
    {
        try{
               foreach (string docId in arrayDocs)
               {
                       int.TryParse(docId, out id);
                       dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
               }
               return Json("Success");
        } 
        catch 
        {
               return Json("Error");
        }
    }


    var sendDocsToDelete = function (docsArray) {
        $.ajax({
            type: 'POST',
            url: 'Main/DeleteDocuments',
            data: docsArray,
            contentType: 'application/json; charset=utf-8',
            datatype: 'json',
            success: function (result) {
                alert('Success ' + result.d);
            },
            error: function (result) {
                alert('Fail ' + result.d);
            }
        });
    }

Any ideas about this issue ? I hoped I was clear enough. Do not hesitate if you need more details.

Upvotes: 4

Views: 37368

Answers (4)

Sachin
Sachin

Reputation: 2148

If you are passing an integer array properly from $.ajax (i.e. your docsArray should be having value like [15,18,25,30,42,49]) then you should try :

[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
    //int id; 
    //string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
  try {
    foreach (int docId in docsArray)
    {
        //int.TryParse(docId, out id);
        dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
    }
    return "Success ";
  }
  catch {
        return "Error";
  }
}

Update :

Your javascript code should be :

var sendDocsToDelete = function (docsArray) {
    $.ajax({
        type: 'POST',
        url: 'Main/DeleteDocuments',
        data: JSON.stringify(docsArray),
        contentType: 'application/json; charset=utf-8',
        datatype: 'json',
        success: function (result) {
            alert('Success ');
        },
        error: function (result) {
            alert('Fail ');
        }
    });
}

Upvotes: 5

Rajshekar Reddy
Rajshekar Reddy

Reputation: 18987

Make these changes to your code.


In Jquery

data: docsArray, no need to stringify the array


In Controller

    [Authorize]                                                //remove [WebMethod]
    public ActionResult DeleteDocuments(string[] docsToDelete) //Add ActionResult, Change parameter to accept array
    {
        int id; 
        string[] arrayDocs = docsToDelete;     //no need of deserilization

        foreach (string docId in arrayDocs)
        {
            int.TryParse(docId, out id);
            dal.DeleteDocument(id); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
        }

       return Json(id);    //return id back to ajax call...
    }

Upvotes: 0

Lokesh_Ram
Lokesh_Ram

Reputation: 391

Try changing your ajax data to something like this..

 data : JSON.stringify({'docsToDelete':docsArray}),

Upvotes: 0

dyedgreen
dyedgreen

Reputation: 40

Maybe the datatype in the JSON array is not a string? (This could happen if you have an array in the form of [45,64,34,6], or a mixed one like [345,"wef4"]).

To make sure something is a string in Javascript you can do this: var string = "".concat(otherVar);

Upvotes: 0

Related Questions