1

I have code that I pass from jQuery to my ASP.Net MVC controller and it works fine. I am now trying to replicate the same functionality in a new situation and the parameter shows up as null when I put a breakpoint in my controller code.

Can anyone see anything wrong with the code below. In firebug I see that calendarIds is a perfectly populated array but it shows up as null on the server side.

Here is my jQuery code:

var calendarIds = [];

$('#box2View option').each(function () {
    calendarIds.push($(this).val());
});

$.post(
    '/EventCalendar/UpdateVisibleCalendars/', 
    { calendarIds: calendarIds }, 
    function (data) {
        //do some callback stuff here (not relevant for question)
    }, 
    "html"
);

Here is my controller code

public ActionResult UpdateVisibleCalendars(int[] calendarIds)
{
    // right here i check calendarIds and its always NULL :(
    return null;
}
1
  • Perhaps because you will post calendarIds=1,2,3,4,5 where as it is expecting calendarIds=1&calendarIds=2&calendarIds=3... Commented Dec 8, 2011 at 16:59

1 Answer 1

2

Use $.ajax() which allows you to set the traditional flag to true:

$.ajax({
    url: '/EventCalendar/UpdateVisibleCalendars/',
    type: 'POST',
    traditional: true,
    data: { calendarIds: calendarIds },
    dataType: 'html',
    success: function (data) {

    }
});

Now the POST body will look like this:

calendarIds=1&calendarIds=2&calendarIds=3

With tgraditional=false (which is the default starting from jQuery 1.4) the POST body looks like this:

calendarIds[]=1&calendarIds[]=2&calendarIds[]=3

And by consulting this blog post you will understand that only the first is compatible with the default model binder.

The jQuery's traditional flag is well explained in the $.param() section.

Sign up to request clarification or add additional context in comments.

2 Comments

yup . . i now see that jQuery.ajaxSettings.traditional = true; was set in my working use case . .i knew there had to be something silly . .
@leora, yeap, that's why you should should always look at your js debugging tool (FireBug, Chrome Developer Tools, ...) what exactly is posted to the server during the AJAX request. Things like this are becoming immediately obvious.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.