Michael Carreon
Michael Carreon

Reputation: 59

How to use Ajax (Jquery) to send arrays to the Controller (MVC)

I've seen a variety of ways people do it, but It's still failing to set the values for the arrays "comments" and "commentCriterions" in the controller. Any help would be much appreciated.

Edit: I managed to use JSON.stringify

data: {
            'comments': JSON.stringify(comments),

The array is set, but set incorrectly

 comments[0] = "[\"zxczxczx\",\"Another boring comment\",\"Why is this broken?!\",\"GASP!\"]"

JQuery

function saveComment(popupId) {
    var textArea = popupId.find('@commentClass');
    var comments = [];
    var commentCriterions = [];
    for (var i = 0; i < textArea.length; i++) {
        comments[i] = textArea.val();
        commentCriterions[i] = textArea.attr("data-criterionid");
    }

    $.ajax({
        url: "SaveComment",
        method: "post",
        dataType: 'json',
        traditonal: true,
        data: {
            'comments': comments,
            'commentCriterions': commentCriterions,
            'observationId': observationId,
            'reviewingId': '@reviewingId'
        },
        success: function (status) {
            if (status == "False") {
                alert("The ID number of the person currently being reviewed has changed, please refresh the page and try again. Any changes to this observation will not be saved.")
            }
        },
    })
}

Controller

public bool SaveComment(string[] comments, string[] commentCriterions, string observationId, string reviewingId)
    {
        int breakPoint = 0;
        return true;
    }

After messing with the function this is what the ajax call looks like, resulting in a 500 (Internal Server Error) after setting contentType in ajax.

    $.ajax({
        type: "POST",
        url: "SaveComment",
        dataType: "json",
        data: {
            'comments': JSON.stringify(comments),
            'commentCriterions': JSON.stringify(commentCriterions),
            'observationId': JSON.stringify(observationId),
            'reviewingId': JSON.stringify('986509040'),
        },
        contentType: 'application/json; charset=utf-8',
        traditonal: true,
        success: function (status) {
            if (status == "False") {
                alert("The ID number of the person currently being reviewed has changed, please refresh the page and try again. Any changes to this observation will not be saved.")
            }
        },
    })

Upvotes: 1

Views: 2115

Answers (1)

user3559349
user3559349

Reputation:

When posting arrays using traditional: true, you need to stringify your data and include contentType: "application/json; charset=utf-8",

var data = { comments: comments, commentCriterions: commentCriterions, observationId: observationId, reviewingId: @reviewingId };
$.ajax({
  url: '@Url.Action("SaveComment")'; // always use @Url.Action!
  method: "post",
  dataType: 'json',
  traditonal: true,
  contentType: "application/json; charset=utf-8", // add this
  data: JSON.stringify(data), // change this
  success: function (status) {
    if (status == "False") {
      alert("The ID number of the person currently being reviewed has changed, please refresh the page and try again. Any changes to this observation will not be saved.")
    }
  }
})

Side notes

  1. You can use the jQuery .map() function to easily generate your arrays, for example var comments = $(someSelector).map(function () { return $(this).val(); }).get();
  2. Consider returning null rather than return Json(false);. Then its just if(!success) { alert(..); }

Upvotes: 1

Related Questions