Pass Array to MVC Action via Ajax

Pass array to mvc Action via AJAX

Set the traditional property to true before making the get call.
i.e.:

jQuery.ajaxSettings.traditional = true

$.get('/controller/MyAction', { vals: arrayOfValues }, function (data) {...

How pass int array from jquery ajax to asp.net mvc action

If you want to send values using traditional encoding then you shouldn't JSON encode the data you're sending. As such, remove the JSON.strigify() call, as well as the contentType. Try this:

$.ajax({
url: url,
type: 'POST',
dataType: "json",
traditional: true,
data: { ids: values }
});

Passing array via Ajax to MVC Action

This is what worked on my end:

jQuery ajax method:

$.ajax({
contentType: "application/json; charset=utf-8",
dataType: 'json',
type: 'POST',
url: '@Url.Action("MonthsToAdd")',
data: JSON.stringify(months),
success: function (response) {
alert("success.");
}
});

Controller action:

[HttpPost]
public async Task<IActionResult> MonthsToAdd([FromBody] List<string> months)

{
// Add [FromBody]
}

Pass an array as parameter to a controller from an ajax call in JavaScript

If you are passing an integer array properly from $.ajax (i.e. your docsArray should be having value like [15,18,25,30,42,49]) then you should try :

[Authorize]
public ActionResult DeleteDocuments(int[] docsArray)
{
//int id;
//string[] arrayDocs = JsonConvert.DeserializeObject<string[]>(docsToDelete);
try {
foreach (int docId in docsArray)
{
//int.TryParse(docId, out id);
dal.DeleteDocument(docId); // dal = DataAccessLayer is the class which interacts with the database by executing queries (select, delete, update...)
}
return "Success ";
}
catch {
return "Error";
}
}

Update :

Your javascript code should be :

var sendDocsToDelete = function (docsArray) {
$.ajax({
type: 'POST',
url: 'Main/DeleteDocuments',
data: JSON.stringify(docsArray),
contentType: 'application/json; charset=utf-8',
datatype: 'json',
success: function (result) {
alert('Success ');
},
error: function (result) {
alert('Fail ');
}
});
}

Error with ajax request when passing array to MVC action method (Web API)

You cannot do this! It is by design that at most one parameter is allowed to read from the message body. Hence, this will not work.

The reason for this rule is that the request body might be stored in a non-buffered stream that can only be read once.

https://learn.microsoft.com/en-us/aspnet/web-api/overview/formats-and-model-binding/parameter-binding-in-aspnet-web-api

There a few workarounds that you can use to make this work:

  1. Use both POST and QueryString Parameters in Conjunction
  2. Use a single Object that wraps the two Parameters
  3. Use JObject to parse multiple Property Values out of an Object

https://weblog.west-wind.com/posts/2012/May/08/Passing-multiple-POST-parameters-to-Web-API-Controller-Methods

Pass array of objects to MVC Controller Action via JQuery AJAX, Action Parameter is always null

Your action parameter is null because you have to fix the way you are sending the data property from your ajax to this:

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

And finally you have another possible problem when inserting the data in the array. I mean this line:

DATA.push("{'MIXINGNO':'" + MIXINGNO + "','DATE': '" + DATE + "','INVOICEDETAILID': '" + INVOICEDETAILID + "','CARET': '" + CARET + "','PRICE': '" + PRICE + "','DETAILS': '" + DETAILS + "'}");

You are trying to insert into the array objects like they already are objects type JSON, the way you have to do this is inserting them like javascript normal objects, like this:

DATA.push({
MIXINGNO: MIXINGNO,
DATE: DATE,
INVOICEDETAILID: INVOICEDETAILID,
CARET: CARET,
PRICE: PRICE,
DETAILS: DETAILS
});

Passing array of objects to Controller Action using jQuery ajax request using .NET Core 2.2 doesn't work

[Edit]
Change the js as below:

    function toInt(str){
var i = parseInt(str);
return i ? i : 0;
}

$("#MarksTable tbody tr").each(function () {

var obj = {};
obj.StudentID = 1;
obj.ExamTimeTableID = 1;
obj.ClassActivity = toInt( $(this).find("td:eq(5) input").val());
obj.IsPresent =toInt( $(this).find("td:eq(7) input").val());
obj.Assignment = toInt( $(this).find("td:eq(6) input").val());
obj.MidTerm =toInt( $(this).find("td:eq(3) input").val());
obj.Final = toInt( $(this).find("td:eq(4) input").val());

datalist.push(obj);
});

This will make sure the empty input to 0 instead of null.


That's because on your server side you're declaring the ClassActivity/ClassActivity/Assignment/... as int type but your js send all them as string. For example, the Payload sent to server will be something like:

[{"StudentID":1,"ExamTimeTableID":1,"ClassActivity":"3","Assignment":"aa","MidTerm":"333333333","Final":"3333"},{"StudentID":1,"ExamTimeTableID":1,"ClassActivity":"","Assignment":"s","MidTerm":"2","Final":"1"},{"StudentID":1,"ExamTimeTableID":1,"ClassActivity":"3","Assignment":"","MidTerm":"2","Final":"1"}]

Please either change the property type or convert the $(this).find("td:eq(7) input").val() result (a string) to int/bool/... type before sending them.



Related Topics



Leave a reply



Submit