Sending empty array to webapi - javascript

I want to POST an empty javascript array [] to webAPI and have it create an empty list of integers. I also want it so if I post javascript null to webAPI that it assigns null to the list of integers.
JS:
var intArray = [];
$.ajax({
type: 'POST',
url: '/api/ListOfInts',
data: {'' : intArray},
dataType: 'json'
});
c# webapi
[HttpPost]
public void ListOfInts([FromBody]List<int> input)
Problem 1) Jquery refuses to send data {'' : []} as the post payload. As soon as I add something in the array it works such as {'' : [1,2,3]}
Problem 2) Passing empty js array to controller gives null Based on what i read even if I do get it to post an empty array, it will initialize the list as null. Discussed solutions have it so that the list is always initializes as empty but I don't want that. I want it to be null in some case (when null/undefined is sent to it) and when [] is sent it should initialize as empty.
Edit: See https://www.asp.net/web-api/overview/advanced/sending-html-form-data-part-1 about why I am using {'' : []}

Use JSON.stringify(intArray) and contentType: 'application/json' works for me:
$.ajax({
url: "/api/values",
method: "POST",
contentType: 'application/json',
data: JSON.stringify([])
});
$.ajax({
url: "/api/values",
method: "POST",
contentType: 'application/json',
data: null
});
$.ajax({
url: "/api/values",
method: "POST",
contentType: 'application/json',
data: JSON.stringify([1, 2, 3])
});

data: {'' : intArray},
a blank key name is not allowed in JSON.
Just send the array itself.
data: intArray,

1. Use JSON.stringify() to convert javascript object to JSON string.
2. Use contentType: 'application/json' as it is correct MIME media type for JSON. What is the correct JSON content type?
3 dataType is not necessary
data: JSON.stringify(intArray),
contentType: 'application/json'

Related

Passing list of integers from AJAX call to C# method returns null

I am trying to pass an array of integers from my client-side javascript to server-side C# using ajax. However it always comes up as null in code-behind. I can't seem to find the issue here. I had a similar ajax method but with an array of strings and it works, but it doesn't with integers?
My ajax method:
var theList = [1,2,3,4,5];
$.ajax({
type: 'POST',
url: 'MyPage?handler=SaveList',
dataType: 'json',
contentType:'application/json; charset=utf-8',
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify({ theList: theList }),
success: function(data){
alert("Success");
}
});
My code-behind:
public JsonResult OnPostSaveList([FromBody]int[] theList) //<<<Returns 'null'
{
foreach(int data in theList){
//save to datebase
}
return new JsonResult("Done");
}
The issue here is I get a null value from theList in the code-behind.
Checking the JSON.stringify, it seems to be passing "[1,2,3,4,5]". Not sure if there is a type mis-match here.
The Max value of int32 is 2147483647, while 1609430400000 is out of range, so you receive the null value.
Instead of int[], you can use long[] to receive the value.
var theList = [1609430400000, 1609516800000, 1609603200000];
$.ajax({
type: 'POST',
url: 'Index?handler=SaveList',
dataType: 'json',
contentType: 'application/json; charset=utf-8',
headers: {
RequestVerificationToken:
$('input:hidden[name="__RequestVerificationToken"]').val()
},
data: JSON.stringify(theList),
success: function (data) {
alert("Success");
}
});
Handler:
public JsonResult OnPostSaveList([FromBody] long[] theList) //<<<Returns 'null'
{
foreach (var data in theList)
{
//save to datebase
}
return new JsonResult("Done");
}
Request Payload:
Result:

how to pass java script values to controller using post method in .net core application?

I am developing .net core application.i need to pass java script values to my controller using Post method. i am using java script code is below
data = {'imageValue':'some test'}
$.ajax({
type: 'Post',
url: '/Home/UploadData',
dataType: 'json',
contentType: 'application/json',
data: data,
success: function (data) {
alert(data);
console.log('sample');
},
error: function(){
}
});
my controller is
[HttpPost]public string UploadData([FromBody] string imageValue)
{return imageValue;} but imageValue always it return null.if any mistake in my code please solve the problem.
When you make the ajax call, you should stringify the javascript object and send it. You can use the JSON.stringify method to convert the js object to it's JSON string equivalent.
var data = {'imageValue':'some test'}
$.ajax({
type: 'Post',
url: '/Home/UploadData',
dataType: 'json',
contentType: 'application/json',
data: JSON.stringify(data),
success: function (data) {
console.log('sample', data);
},
error: function(){
}
});
Now since the ajax call is sending the data in the request body (since it is a POST request),You need to decorate the HttpPost action method parameter with [FromBody] attribute so that model binder knows it should read the data from the request body and map to the method parameter(YourViewModel) object.
public IActionResult UploadData([FromBody] YourViewModel d)
{
return Json(d);
}

jquery not posting array data

ive tried 10 different solutions to this issue on stackoverflow and none of them work, heres the issue, i need to post a array via ajax to a url
simple right?
the array comes from post values like this $_post[xxx] which i store in a var.
i mocked up a js function, that has the same error, instead of passing the array i just included as a var in the function, problem is the data is not gettin posted to the url.
pastebin link: http://pastebin.com/8ivWqJ8g
function generateImage() {
var Imagedata = [];
Imagedata['id'] = 1;
Imagedata['type'] = 'some type';
var url = '';
$.ajax({
url: url,
processData: false,
dataType: 'JSON',
data: JSON.stringify(Imagedata) ,
method:'POST',
async: false
});
Named properties of arrays do not get serialised when you convert the data to JSON.
Arrays are supposed to hold an ordered set of values, not an arbitrary set of name:value pairs.
Use a plain object ({}) not an array.
Asides:
Don't use processData: false unless you are passing something that isn't a string or an object to data (e.g. a FormData object). Since you are passing a string, it is harmless, but pointless. If you were passing an object (which you probably should be, see below), it would break things.
Don't use async: false. It is deprecated, and harms the user experience (since it locks up the JS thread until the response arrives).
If you want to populate PHP's $_POST then don't format your data as JSON. Pass the object directly to data: without using JSON.stringify.
If you do want to make a JSON formatted request, then don't forget to set the contentType.
function generateImage() {
var Imagedata = {
id: 1,
type: "some type"
};
var url = '';
$.ajax({
url: url,
dataType: 'JSON',
data: Imagedata,
method: 'POST'
});
// or …
$.ajax({
url: url,
dataType: 'JSON',
contentType: "application/json",
data: JSON.stringify(Imagedata),
method: 'POST'
});
}
data should be an Object like this:
$.ajax({
url: 'http://...',
dataType: 'JSON',
data: {id: 1, type: 'some type'} ,
method:'POST',
async: false
});

Populate a html div with json data received from a server

I need to have a html div populated with the json data received from the server which is a json-rpc server and it retruns an application/jsson-rpc content type and i can see the result in the chrome and firefox dev tools... I need to view it as part of the page inside a given div
i have this script to populate the mybox div but it gives nothing
var returnedinfo;
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
I also tied having the populating function outside the ajax block when the request is done
request.done(function(msg) {
$("#mybox").text(msg);
});
This just return an empty array like this
[object Object]
and nothing else help will be appreciated.
you need to append the key of the json item.
$("#mybox").html(json.key);
Add dataType to your ajax request.
var request = $.ajax ({
url: "/url",
type: "POST",
data: JSON.stringify(data),
dataType: "json",
success: function(json) {
alert("success sent ajax");
$("#mybox").html(json);
returnedinfo = json;
});
try this my working example
look contentType and html function to replace html of mybox element
$.ajax({
type: 'POST',
data: JSON.stringify(data),
contentType: "application/json; charset=utf-8",
url: 'url',
success: function (dataRes) {
$('#mybox').html(dataRes);
},
error: function(a,b,c) {
}
});
Note that in this case dataRes in success function is an html string like <strong>test</strong>. If your server side function returns a json object you should add dataType: 'json' to ajax request and then you can use properties of dataRes object like here $('#mybox').html(dataRes.property1);

JavaScript array getting encoded when posting jQuery

I'm trying to post part of my Knockout viewmodel to our server using jQuery.Ajax.
When I build the data object it looks fine in the console, but when it gets sent via the jQuery Ajax Post the array within gets encoded. The results on the other end are readable by the server, so it works, but it disturbs me greatly (the payload is bigger for one thing).
Here's the code:
var items = $.map(self.Items(), function (item) {
return item.Key() ? {
Key: item.Key(),
PromoCode: item.PromoCode,
Qty: parseInt(item.Qty(), 10)
} : undefined;
}),
data = {
"InEditMode": true,
"Items": items
};
$.ajax({
url: '/api/order/',
type: 'POST',
data: data,
dataType: "json",
success: function (order) {
<snip>
The result as seen by FireBug is this.
Here's the decoded JSON Object
InEditMode true
Items[0][Key] 2730M0ARAX1111AAAAX0
Items[0][PromoCode]
Items[0][Qty] 3
Items[1][Key] 2730M0ARCX1111AAAAX0
Items[1][PromoCode]
Items[1][Qty] 5
Here's the Raw view
InEditMode=true&
Items%5B0%5D%5BKey%5D=2730M0ARAX1111AAAAX0&
Items%5B0%5D%5BPromoCode%5D=&
Items%5B0%5D%5BQty%5D=3&
Items%5B1%5D%5BKey%5D=2730M0ARCX1111AAAAX0&
Items%5B1%5D%5BPromoCode%5D=&
Items%5B1%5D%5BQty%5D=5
Like #codenoire said in his comment, you aren't specifying the content type. Add contentType: 'application/json; charset=utf-8' to your $.ajax call, like so:
$.ajax({
url: '/api/order/',
type: 'POST',
data: data,
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (order) {
<snip>
I think you need to stringify your JSON object before you post it. Use JSON.stringify(data) before you post it.
I was so close! The answer is a combination of rwisch45 and Saeedses
I had already tried adding the contentType before, but that caused it to break and I hadn't pursued it any further then that.
the solution is to add the content type AND JSON.stringify it, as so.
$.ajax({
url: '/api/order/',
type: 'POST',
data: JSON.stringify(data),
dataType: "json",
contentType: 'application/json; charset=utf-8',
success: function (order) {
Thanks all for your help!

Categories