Pirzada
Pirzada

Reputation: 4713

JQuery Ajax to pass array. Need help

I been struggling and looking everywhere but can not find solution to this. I want to pass Array data in $.ajax but don't know how to. Below is the code.

$("#procressGrid").click(function () {
         var dataArray = [];
         $.each($(".gridTable tr:not(.gridTitleRow)"), function(a, b){
                var id = $("input.idField", b).val();
                var code = $("input[name='code']", b).val();

                dataArray.push({
                    "id": id,
                    "code": code
                })

         });

         $.ajax({
                url: "/HeaderMenu/So",
                type: "POST",

                data: { backerEntries[]: dataArray } 

                dataType: "json",
                contentType: "application/json; charset=utf-8",
                beforeSend: function () { $("#statusDropdown").fadeIn(); },
                complete: function () { $("#statusDropdown").fadeOut(); },
                success: function (data) {

                    if (data.Status == "Success") {

                    } else {

                    }
                },
                error: function () {
                    $("#error").show().html("An error has occured!!!");
                }
            });
    });

and what to declare in MVC3 controller?

 public ActionResult So(Array backerEntries)
        {
            //var b = a;


                return Json(new { status = "Success", message = "Passed" });


        }

Upvotes: 3

Views: 3859

Answers (4)

WooDzu
WooDzu

Reputation: 4866

  var fields = $("
      .gridTable tr:not(.gridTitleRow) input.idField,
      .gridTable tr:not(.gridTitleRow) input[name='code']
").serializeArray();

$.ajax({ ...

data: { backerEntries: fields } 

... });

can U try this for serializing your Array?

Upvotes: 0

excanoe
excanoe

Reputation: 696

Try JSON.stringify() on client side to serialize data to string and then on server side try to decode that data.

You will get array or hash that you need.

JSON

Upvotes: 0

DropTheNerd
DropTheNerd

Reputation: 134

Will this work for you?

 var dataArray = new Array();

 // fill your array     

 $.ajax({
     url: "/HeaderMenu/So",
     type: "POST",
     data: {'backerEntries' : dataArray},
     // the rest of your code
 });

Upvotes: 0

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

I would change your $.ajax call:

$.ajax({
   /*snip */
   data: dataArray
}); 

And on the server-side create a view model to bind to:

public class BackerEntry
{
    public string Id { get; set; }
    public string Code { get; set; }
}

Now your action would take an array of those types:

public ActionResult So(BackerEntry[] backerEntries) 
{
    // ...
}

Upvotes: 4

Related Questions