1

I'm using $.post() to post an array of integer values to my controller.

Here's how I construct my array:

var ratings = [];
$('#ratings input[name=newReviewRatings]').each(function () {
    ratings.push($(this).val());
});

Here's how I'm posting it to the controller:

$.post('@Url.Action("CreateReview", "Provider")',
{
    id: providerId,
    ratings: ratings,
    comment: comment
});

Here's the form data that gets posted:

{id=437baf29-4196-4966-88de-a8fde87ef68d&ratings%5b%5d=1&ratings%5b%5d=2&ratings%5b%5d=3&ratings%5b%5d=4&ratings%5b%5d=5&comment=Comments}

And here's my controller signature:

public ActionResult CreateReview(Guid id, int[] ratings, string comment)
{
    // ....
}

That seems like that should be right, but ratings is always null. Can anyone see what I'm missing?

I also tried string[] ratings and got the same result. I also saw a suggestion to pass the array using JSON.stringify(ratings) but that didn't seem to help either.

2

2 Answers 2

4

In adition to converting the post data to json, you can also set the traditional param to true. This will cause jQuery to use the correct post format for MVC.

jQuery.ajaxSettings.traditional = true;

$.post('@Url.Action("CreateReview", "Home")',
    {
        id: 'GUID STRING HERE',
        ratings: [1, 2, 3],
        comment: 'adfef'
    });
Sign up to request clarification or add additional context in comments.

Comments

0

Try to specify contentType like this:

$.ajax({
  url:url,
  type:"POST",
  data:data,
  contentType:"application/json; charset=utf-8",
  dataType:"json",
  success: function(){
    ...
  }
})

2 Comments

Only if you convert the data to json first.
This answer is incomplete. But I was able to get it working by setting data to JSON.stringify({ id: providerId, ratings: ratings, comment: comment }).

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.