pass array of numbers from ajax to controller - javascript

I know this is a popular topic and I've tried all of the solutions I could find already out there to no avail. I've used all the solutions included for this questions: Pass a List from javascript to controller. I've simplified my test to ridiculously simple. I get into the controller but my controller input param is {int[0]}. I confirmed my array data looks good in the JavaScript and ajax call.
Can anyone please tell me what I am missing?
JavaScript Code
var selectedIds = [];
selectedIds.push(565);
selectedIds.push(573);
selectedIds.push(571);
// selectedIds = [565, 573, 571]
$.ajax({
type: "POST",
traditional: true,
dataType: "json",
data: { "ids": JSON.stringify(selectedIds) },
//data: { "ids": selectedIds},
//data: { ids: selectedIds},
url: "api/services/getbuildingsbyid",
success: function (result) {
return result;
}
});
Controller Code
[HttpPost]
public bool GetBuildingsById(int[] ids)
{
var lookAtIds = ids; // {int[0]}
return true;
}

By using JSON.stringify(selectedIds) you are turning an array of int into a string representation of said array.
The AJAX POST ends up like so:
{ "ids": "[565, 573, 571]" }
instead of
{ "ids": [565, 573, 571] }
If instead you just use the variable for the data, that should resolve the issue:
data: { "ids": selectedIds },
Edit-
Working backwards, by setting a variable to the data we can see the following:
var data = {"ids": JSON.stringify(selectedIds)}
typeof(data["ids"]) // string
data["ids"][0] // '['
data = {"ids": selectedIds}
typeof(data["ids"]) // object
data["ids"][0] // 565

I use:
public ActionResult GetBuildingsById(String selectedIds)
{
// this line convert the json to a list of your type, exactly what you want.
IList<int> Ids = new JavaScriptSerializer().Deserialize<IList<int>>(selectedIds);
return Content(ids[0].ToString());
}
This will take you selectedIds = [565, 573, 571]
and create the list of your type List

Related

How to structure a JSON call

I have an endpoint which I call with Axios and the response looks like (for example):
items: [
{
url: "https://api.example1...",
expirationDate: "2019-11-15T00:00:00+01:00"
},
{
url: "https://api.example2...",
expirationDate: "2019-12-20T00:00:00+01:00"
},
{
url: "https://api.example3...",
expirationDate: "2020-01-17T00:00:00+01:00"
},
...and so on.
If I go to one of the url:s in the browser the structure of the JSON is:
fooBar: {
url: "https://api.foo...",
id: "123",
type: "INDEX",
source: "Foobar",
quotes: {
url: "https://api.bar..."
}
},
I need to get the quotes of the two first url:s in items:[] dynamically because they will disappear when the 'expirationDate' is older than today's date.
How can this be achieved? Thanks in advance!
If I understand the requirements correctly you need to:
get the list of items
get item details for first two items (to extract links to quotes)
get quotes for first two items
You can use promise chaining to execute these operations maintaining the order:
const getQuotes = (item) => axios.get(item.url)
.then(resp => axios.get(resp.data.fooBar.quotes.url));
axios.get('/items') // here should be the url that you use to get items array
.then(resp => resp.data.slice(0, 2).map(getQuotes))
.then(quotes => Promise.all(quotes))
.then(quotes => {
console.log(quotes);
});
Please find my proposal below. I gave two examples. You can get the whole quotes object, or just the URL inside the quotes object.
This is just a console log, but you can easily ie. append this data to a div in the html or pass this URL to some other function.
$(function() {
const address = 'https://api.example1...';
function loadQuotes() {
$.ajax({
url: address,
dataType: 'json',
}).done(function(response) {
response.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});
});
}
loadQuotes();
});
If these are nested objects, just append fooBar.
For example change the .done part to:
.done(function(response) {
let qqq = response.quotes
quotes.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});

Setting up a Todo List server

I'm fairly new to Javascript, Node.js and JSON. I'm supposed to build some sort of Todo list application, where the user sends his todo to a server. I've already created the HTML and Javascript to execute the basic operation without the server.
I'm using the following program/languages in order to complete my assignment:
Vagrant (various NPM modules)
VirtualBox
Javascript (jQuery)
Currently i'm trying to send the data via the following lines of code:
//Create (simplified) "task"
item["id"] = task.dataset.id;
item["taskname"] = task.dataset.taskname;
item = JSON.stringify(item);
//Send code
$.ajax({
url: '/addtodo',
type: 'post',
dataType: 'json',
success: function (data) {
console.log(data);
},
data: item
});
Where as on the receiving side, I try to receive the data using the following lines of code:
app.post("/addtodo", function (req, res) {
var newTodo = req.body;
fs.writeFile("Somefile.json", JSON.parse(newTodo), function(err) {
if(err) {
res.json({"message":"Storing data failed"});
} else {
res.json({"message":"Data stored successfully"});
}
});
});
My objective is to get something like this in "Somefile.json"
[{
"id" : 2,
"taskname" : "Example task 2",
},
{
"id" : 2,
"taskname" : "Example task 2",
},
]
For now I get either errors or it changes the Somefile.json into [object Object].
Anyone care to explain what I did wrong and how I should fix it
Edit:
If I do not use JSON.parse i get : [object Object]
If I use JSON.stringify I get {"{\"id\":\"6\",\"taskname\":\"1234\"}":""}
Instead of the
JSON.parse(newToDo);
Use
JSON.stringify(newToDo);
This function will convert the object into a string and will give you the desired output.

Select2 Multiple format to be passed to JSON

I am using the select2 multiple for search box. I am passing these data with JSON and saving it using ajax(JSON stringify).
I just need 2 variables passed, which is the ID(primary key, customized) and the Selection itself.
I managed to save it to the database when only 1 value is selected.
When selecting multiple values, in my console.log, I see something like this
{21,23,25,26}
which is the selection itself.
How do I get it show like this,
Object0->{id:1, selection:21}
Object1->{id:2, selection:23}
Object2->{id:3, selection:25}
Object3->{id:4, selection:26}
Below is the code I am using,
var nature = {
ubtBusinessInfo: businessId, // the primary key
ubtBusinessListing: nature.val() // here is selection
};
Here is the initialization of the select2,
nature
.select2({
allowClear: true,
placeholder: "Filter as you type",
minimumInputLength: 3,
multiple: true,
ajax: {
url: 'home/umkei/info/nature',
dataType: 'json',
quietMillis: 250,
data: function (term, page) {
return { q: term };
},
results: function (data, page) {
return { results: data };
},
cache: true
}
})
nature is defined from(I tried both as below)
var nature = $('[name=nature_business]') OR var nature = $(#nature_business);
I know it must have something to do with the nature.val() usage. Must have been something like array but I dont know how to differentiate/split those data to be key->value pairs.
Thank you.
I got this about last week and thought I'd share my solution.
var nature=[];
var splitnature = nature_business.val().trim().split(',');
var n;
for(n=0; n<=splitnature.length-1;n++){
nature.push({
ubtBusinessListing: splitnature[n],
ubtBusinessInfo: businessId
});
}

Adding keys to objects in a parse object

Im working with the parse javascript sdk and i want to add a key to an object in a Parse 'object' when saving it.
For ex:
var saveGif = new SaveGifTags();
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: newGif
}, {
success: function(data) {
console.log(data);
res.json(data);
},
error: function(data) {
console.log(data);
}
});
gifObjects is my object in the Parse Class. I tried to do something like this
gifObjects: gifOjects[gifObj.id] = newGif;
newGif of course is the object i want to save. This gave me an error of gifObjects is not defined. So i tried something like this
gifObjects[gifObj.id] : newGif;
that didnt work either. i want to create something like this:
{
hgs32: {
url: '',
image: ''
},
64522 : {
url: '',
image: ''
}
}
any suggestions?
Figured it out. Not sure what the downvote is for, but i had to create the object before i saved it.
var gifObjects = {};
gifObjects[gifObj.id] = newGif;
and then the save
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: gifObjects
},

Is there a more standardized way in javascript of converting (serializing) non-form data for use with ajax?

I am using asp.net mvc 3 and have strongly typed models to pass to. The models will accept data if it is in a proper form. This form dictates that the data be in NameMatchingModel=value separated by &. For example, if I had:
viewmodel:
public class CarViewModel
{
public Car Car { get; set; }
}
public class Car
{
public string Make { get; set; }
public string Model { get; set; }
}
and then I had a method accepting this ViewModel
public ActionResult AcceptCarVM( CarViewModel model )
{
//TODO: use car data
return View();
}
Now, I want to pass in the viewmodel filled with some details for the car. Is there a better approach to doing this than this manual way?
var carMake = "Ford";
var carModel = "Pinto";
var viewModelData = "Car.Make=" + carMake + "&Car.Model=" + carModel;
var encodeData = encodeURIComponent(viewModelData);
$.ajax({
url: "#(Url.Action("AcceptCarVM"))",
type: 'GET',
data: encodeData,
success: function (result) {
//TODO: use result
}
});
jQuery has a function to serialize query strings
$.param
Here's the documentation
You will of course provide your data in a different manner... But since you're nesting types I could suggest to use the .toDictionary plugin that will correctly serialize JSON objects regardless of their structure, and also convert dates in a way that Asp.net MVC will understand when data binding.
var data = {
Car: {
Make: "Ford",
Model: "Pinto"
}
};
$.ajax({
url: "#(Url.Action("AcceptCarVM"))",
type: 'GET',
data: $.toDictionary(data),
success: function(result) {
// TODO: use result
}
});
or even:
var data = {
Make: "Ford",
Model: "Pinto"
};
$.ajax({
url: "#(Url.Action("AcceptCarVM"))",
type: 'GET',
data: $.toDictionary(data, "Car"), // will provide root object's name
success: function(result) {
// TODO: use result
}
});
The second one is especially useful when you have a controller action that takes two parameters of the same type, so you can provide root object's name the same as action parameter names, so they'll get correctly data bound on the server side ie:
public ActionResult AcceptCarVM(CarViewModel carOne, CarViewModel carTwo) { ... }
Plugin internally uses jQuery functionality so it serializes things reliably and is especially suited for Asp.net MVC back-end.

Categories