2

Is it posible with ajax to send one json-array (array with json objects) and also include a separate parameter to receive in MVC action method?

JavaScript:

var n = {
    number: 1           
};

$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    data: JSON.stringify({jsonObjects:json, number:n}),
    success: function (response) {
        $('#body').html(response)
    }

});

MVC action:

public ActionResult Create(List<JsonObjects> jsonObjects, int? number)

JsonObjects is coming in like it supposed to but number is null.

tereško
  • 58,060
  • 25
  • 98
  • 150
MikeAlike234
  • 759
  • 2
  • 12
  • 29

2 Answers2

2

It seems like your n variable declaration is wrong.

Try the following

var n = 1;

$.ajax({
        type: "POST",
        url: url,
        contentType: "application/json; charset=utf-8",
        dataType: "html",
        data: JSON.stringify({jsonObjects:json, number:n}),
        success: function (response) {
            $('#body').html(response)
        }

        }
    });
Flea777
  • 1,012
  • 9
  • 21
0

Try the following code:

var n = 1;

$.ajax({
    type: "POST",
    url: url,
    contentType: "application/json; charset=utf-8",
    dataType: "html",
    data: json+ "&number=" + n,
    success: function (response) {
        $('#body').html(response)
    }

});

I apologise if this doesn't work as I am unable to test this situation exactly, but the following line should be roughly what you are after and has worked for me in similar situations:

data: json+ "&number=" + n,

Also, see this related question which may help you fix your problem.

Community
  • 1
  • 1
Lewis
  • 789
  • 8
  • 20