Keith Barrows
Keith Barrows

Reputation: 25308

jQuery ajax post on asp.net mvc2

I have a jQuery function that is called when the "submit" button is clicked:

function SubmitForm() {
    var idList = [];
    var list = $('#TableAdminPortfolio .CheckBoxProjects');
    list.each(function () {
        var id = $(this).closest('td').children('.hiddenId').val(); // parseInt()
        idList.push(id);
    });

    $.ajax({
        url: $(this).href,
        type: 'POST',
        data: idList,
        success: function (result) {alert('Successful');},
        error: function (result)  {alert('Error');}

    });
}

My controller looks like:

[Transaction]
[AcceptVerbs(HttpVerbs.Post)]
public ActionResult Index(IEnumerable<int> projects)
{
    ...
}

The paramater (projects) is always null. I've stepped through my jQuery code inspecting it each step of the way and the idList is definitely populated. I've also tried my $ajax like this:

$.ajax({
        url: $(this).href,
        type: 'POST',
        data: { projects : idList },
        success: function (result) {alert('Successful');},
        error: function (result)  {alert('Error');}

    });

And still the same results. Any ideas what is going on? And yes, I have a reason for doing an Ajax Post rather then a Form Post.

TIA

NOTE: I am using jQuery v1.6.4 and ASP.NET MVC 2.0.

Upvotes: 3

Views: 1038

Answers (2)

Mark Schultheiss
Mark Schultheiss

Reputation: 34158

try:

 var mylist='{"projects":'+ JSON.stringify(idList)+'}';

then

data:mylist,

Upvotes: 0

Dave Alperovich
Dave Alperovich

Reputation: 32490

try converting your array to json using JSON.stringify

$.ajax({
    url: $(this).href,
    type: 'POST',
    dataType: "json",
    data: JSON.stringify(idList),
    traditional: true,
    success: function (result) {alert('Successful');},
    error: function (result)  {alert('Error');}

});

Upvotes: 2

Related Questions