Gun
Gun

Reputation: 521

Use a call Ajax to send an Array of string to mvc Controller

i'm trying to get the values from the a table column, I put it in an array then send it to my controller. Something very strange happens, you'll see below :

Here is my JS code :

var result = [];

        $('td:nth-child(' + columnNbr + ')').each(function () {
            var t = $(this).html();
            result.push(t);
        });

        $.ajax({
            type: "POST",
            url: '@Url.Action("UpdateTable", "Home")',
            dataType: "html",
            traditional: true,
            data: { values: result },
            success: function (data) {
            }
        });

My Array "result" is well populated with the values I need.

Here is my controller:

public ActionResult UpdateTable(List<string> values)
{
    return View("index");
}

This returns a 500 internal error. What's driving me crazy is this -> if I modify my JS from what I posted to this:

        //$('td:nth-child(' + columnNbr + ')').each(function () {
        //    var t = $(this).html();
        //    result.push(t);
        //});

        result.push("test1");
        result.push("test2");

The Ajax call works fine ... I checked the "typeof $.(this).html()" and all are strings!

I have no idea what's wrong.

Upvotes: 2

Views: 971

Answers (2)

Vixed
Vixed

Reputation: 3499

Why don't just use $.post()

var result = [];

$('td:nth-child('+columnNbr+')').each(function(){
    result.push($(this).text());
});

$.post('@Url.Action("UpdateTable", "Home")', {values: result});

Or if you need a callback:

$.post('@Url.Action("UpdateTable", "Home")', {values: result}, function(data){
    // what to do
});

Upvotes: 1

lukesUbuntu
lukesUbuntu

Reputation: 517

You just need to change var t = $(this).html(); to var t = $(this).text();

Upvotes: 2

Related Questions