Json data reading in client side in asp.net application - javascript

I have the following data as json:
"Table":[
{
"AF":2000.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":100.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":15000.00
"RegionNumber":2
"RegionName":"Istanbul"
},
{
"AF":31000.00
"RegionNumber":1
"RegionName":"Black Sea"
},
{
"AF":11000.00
"RegionNumber":2
"RegionName":"Istanbul"
}
]
I want to arrange the data in the following format in Javascript.
series: [{
name: 'Black Sea',
data: [2000, 100, 31000],
stack: 'Bookings'
}, {
name: 'Istanbul',
data: [15000,11000,0],
stack: 'Bookings'
}]
How can I accomplish this transformation?

This almost does what you ask and uses Ramda.js too
const data = {
Table: [
{
AF: 2000,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 100,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 15000,
RegionName: "Istanbul",
RegionNumber: 2
},
{
AF: 31000,
RegionName: "Black Sea",
RegionNumber: 1
},
{
AF: 11000,
RegionName: "Istanbul",
RegionNumber: 2
}
]
}
const transfromTableData =
R.pipe(
R.groupBy(R.prop("RegionName")),
R.map(R.pluck("AF")),
R.toPairs,
R.map(R.zipObj(["name", "data"]))
)
const transfromData = (data) => ({
series: transfromTableData(data.Table)
})
console.log(transfromData(data))
<script src="//cdnjs.cloudflare.com/ajax/libs/ramda/0.25.0/ramda.min.js"></script>

In pure JavaScript:
var memo = {}
for (var i in table) {
var item = table[i];
if (memo[item.RegionName] !== undefined) memo[item.RegionName].data.push(item.AF);
else memo[item.RegionName] = {
name: item.RegionName,
data: [item.AF],
stack: 'Bookings'
}
}
var result = {
series: []
};
for (var i in memo) {
result.series.push(memo[i]);
}
console.log(result);

I'm passing arrays of custom objects into List in web methods and it works just fine.
I'm, guessing that you're having a small JSON formatting issue because of the quotes around the property names. Try changing your object to this :
var scoresList = [{TraitID:1, TraitScore:2}, {TraitID:2, TraitScore:5}];
and change your data line to this :
data: JSON.stringify({ scores : scoresList }),
Hope that helps...
UPDATE: working example...
<script type="text/javascript">
$(function () {
var scoresList = [{ TraitID: 1, TraitScore: 2 }, { TraitID: 2, TraitScore: 5}];
$.ajax({ type: "POST",
url: "Tryouts.aspx/Test",
data: JSON.stringify({ scores: scoresList }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (response) {
if (response.d == true) {
alert("success!!!!!");
} else {
alert("problem!!!!!!!!!");
}
},
error: function (xhr) {
alert("ERROR");
}
});
});
</script>
Here's the codebehind :
public class Score
{ // default constructor
public Score() { }
public int TraitID { get; set; }
public double TraitScore { get; set; }
}
[WebMethod]
public static bool Test( List<Score> scores )
{
return true;
}

Related

Get data from RichSnippet JSON and set the same string into other variable

I have this JSON generated from external (Reviews-io) script:
https://widget.reviews.co.uk/rich-snippet/dist.js
richSnippet({
store: "www.storedigital.local",
sku:"6647;6647_5;6647_4;6647_3;6647_11;6647_10;6647_2;6647_1;6647_9;6647_8;6647_7;6647_6",
data:{
"url": "store.stg.gsd.local/1/silla-replica-eames.html",
"description": ``,
"mpn": "6647",
"offers" :[{
"#type":"Offer",
"availability": "http://schema.org/InStock",
"price": "559",
"priceCurrency": "MXN",
"url": "https://store.stg.gsd.localx/1/silla-replica-eames.html",
"priceValidUntil": "2022-05-26",
}],
"brand": {
"#type": "Brand",
"name": "Not Available",
}
}
})
I need to get all the string of numbers in "sku", and then put them in another variable as same format (6647; 6647_1; 6647_2)
I try to get the numbers using this JS but doesn't works
var skucollection = JSON.parse(richSnippet, function (key, value) {
if (key == "sku") {
return new Sku(value);
} else {
return value;
}
});
Can you help me check what I am doing wrong, to get this sku's value string, please?
JSON.parse is not too much? ,handle it as it is internally (a JSON indeed)
var richSnippet = {
store: 'www.storedigital.local',
sku: '6647;6647_5;6647_4;6647_3;6647_11;6647_10;6647_2;6647_1;6647_9;6647_8;6647_7;6647_6',
algomas: [],
data: {
url: 'store.stg.gsd.local/1/silla-replica-eames.html',
description: ``,
mpn: '6647',
offers: [
{
'#type': 'Offer',
availability: 'http://schema.org/InStock',
price: '559',
priceCurrency: 'MXN',
url: 'https://store.stg.gsd.localx/1/silla-replica-eames.html',
priceValidUntil: '2022-05-26',
},
],
brand: {
'#type': 'Brand',
name: 'Not Available',
},
},
};
var test;
Object.keys(richSnippet).forEach((key) => {
if (key == 'sku') {
test = richSnippet[key];
}
});
console.log('test', test);

form Data set values from web service response

I am trying to set table values from webservice response.
Iam getting my web service response like this.but if he response is like this means it is not getting set there.This response can be dynamic.
0:{name: "image.png", base64: "iVBORw"}
1:{name: "download.png", base64: "iVBO"}
2:{name: "test-animation.gif", base64: "R0lGODlhLAEs"}
How can i change it to??
[["image.png", "iVBORw"],["download.png", "iVBO"],[test-animation.gif", "R0lGODlhLAEs"]]
here it is what iam trying
$.cordys.ajax({
method: "somewebservice",
namespace: "Package",
parameters: {
emailid:mailidvalue
},
dataType: '* json',
success: function (result) {
output=result;
bodycontent=output["data"]["body"];
var attachvalue=result.data.tuple;
$('#attachmenttable').DataTable( {
"data": attachvalue,
columns: [
{ title: "File Name" },
{ title: "Base64" }
]
} );
},
error: function(err){
console.log(err);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
I see a 1-1 mapping between what you are given and what you desire, therefore use Array.prototype.map() or $.map.
var given = {
0: {
name: "image.png",
base64: "iVBORw"
},
1: {
name: "download.png",
base64: "iVBO"
},
2: {
name: "test-animation.gif",
base64: "R0lGODlhLAEs"
}
};
var desired = Object.keys(given).map(function(key) {
return [ given[key].name, given[key].base64 ];
});
console.log(desired);
var given = {
0: {
name: "image.png",
base64: "iVBORw"
},
1: {
name: "download.png",
base64: "iVBO"
},
2: {
name: "test-animation.gif",
base64: "R0lGODlhLAEs"
}
};
var desired = $.map(given, function (value, key) {
return [[ given[key].name, given[key].base64 ]];
});
console.log(desired);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Insert dynamic listbox options in Tinymce popup editor

I am trying to create dynamic listbox values but getting this error in console:
Uncaught TypeError: Cannot assign to read only property 'active' of [
Here's my code( pasting only the code for listbox ):
body: [
{
type: 'listbox',
name: 'type',
label: 'Panel Type',
value: type,
'values': get_author_list(),
tooltip: 'Select the type of panel you want'
},
]
.....
And I am calling this function to get dynamic list...
function get_author_list() {
var d = "[{text: 'Default', value: 'default'}]";
return d;
}
I am guessing that the values in listbox only takes static var and not dynamic. But I need to insert dynamic values in this list. Please can anyone help me find a workaround. Is there any possibility to insert via ajax?
Thanks, in advance!!
I needed something similar for .NET site. Even though is not great code I hope it can help someone.
tinymce.PluginManager.add('DocumentSelector', function (editor, url) {
// Add a button that opens a window
editor.addButton('DocumentSelector', {
text: 'Document',
icon: false,
title: "Document Selector",
onclick: function () {
var _documentList;
//load all documents
var _data = JSON.stringify({/* Some data */});
$.ajax({
type: "POST",
url: "/api/TinyMCE/GetDocuments",
data: _data,
contentType: "application/json; charset=utf-8",
dataType: "json",
processData: true,
success: function (data) {
_documentList = eval('(' + data + ')');
// Open window
editor.windowManager.open({
title: 'Document Selector',
body: [
{
type: 'listbox',
name: 'DocURL',
label: 'Documents',
values: _documentList
},
{
type: 'textbox'
, name: 'TextToDisplay'
, value: _text
, label: 'Text To Display'
},
{
type: 'textbox'
, name: 'TitleToDisplay'
, value: _title
, label: 'Title'
},
{
type: 'listbox',
name: 'TheTarget',
label: 'Target',
values: [{ text: 'None', value: "_self" }, { text: 'New Window', value: "_blank" }],
value: _target
}
],
onsubmit: function (e) {
// Insert content when the window form is submitted
}
});
},
error: function (xhr, status, error) {
alert("Error! " + xhr.status + "\n" + error);
}
});
}
});
});
And here it is some of the Behind code
public class TinyMCEController : ApiController
{
public class DocumentsInfo
{
// Some data
}
public class DocumentList
{
public string text { get; set; }
public string value { get; set; }
}
[HttpPost]
[ActionName("GetDocuments")]
public object GetDocuments(DocumentsInfo docInfo)
{
//Test data
List<DocumentList> _DocumentList = new List<DocumentList>();
_DocumentList.Add(new DocumentList {
text = "Document1.pdf",
value = "value1"
});
_DocumentList.Add(new DocumentList
{
text = "Document2.pdf",
value = "value2"
});
var jsonSerialiser = new JavaScriptSerializer();
var json = jsonSerialiser.Serialize(_DocumentList);
return json;
}
}

Send array of Objects to MVC Controller

I try to send an array of json objects to server:
var objectData = [
{ Description: "Bezeichnung", Value: "1", Name: "Betrag (Brutto)" },
{ Description: "Dies ist die erste Bezeicnung", Value: "101", Name: "11,90" },
{ Description: "Dies ist die zweite Bezeicnung", Value: "12", Name: "11,90" }
];
$.ajax({
url: "/system/createinvoice",
data: JSON.stringify({ pos: objectData }) ,
dataType: 'json',
type: 'POST',
});
C#
public class InvoicePos
{
public string Description { get; set; }
public Nullable<double> Value { get; set; }
public string Name { get; set; }
}
[POST("/system/createinvoice")]
public void newquestion2(InvoicePos[] pos)
{
// pos is always null
}
The dataType property is saying what you expect back from the server. Try setting the contentType:
contentType: 'application/json'
Try
data: JSON.stringify({ pos: #objectData })
Also, check what is being rendered in the View through the browser. The reason you are getting null is likely because JavaScript is not getting a proper value.
function SendArrayOfObjects()
{
var things = [{ id: 1, color: 'red' }, { id: 2, color: 'blue' }, { id: 3, color: 'yellow' }];
$.ajax({
type: "POST",
url: "<%= ResolveUrl("~/MyServices.aspx/GetData")%>",
data: JSON.stringify({ objdata: things }),
contentType: "application/json;charset=utf-8",
dataType: "json",
success: function()
{
$("#msg").html("data sent successfully!");
},
error: function()
{
$("#msg").html(" Can not send data!");
}
});
}

Dojo Dnd issue: Convert to JSON by Dnd item types with JavaScript

I am using this example using drag and drop from this site:
I am creating containers using Dnd item types example in the same page. Like this;
Source container
var catalog = new dojo.dnd.Source("catalogNode", {
accept: ["inStock,outOfStock"]
});
catalog.insertNodes(false, [
{ data: "Wrist watch", type: ["inStock"] },
{ data: "Life jacket", type: ["inStock"] },
{ data: "Toy bulldozer", type: ["inStock"] },
{ data: "Vintage microphone", type: ["outOfStock"] },
{ data: "TIE fighter", type: ["outOfStock"] },
{ data: "Apples", type: ["inStock"] },
{ data: "Bananas", type: ["inStock"] },
{ data: "Tomatoes", type: ["outOfStock"] },
{ data: "Bread", type: ["inStock"] }
]);
catalog.forInItems(function(item, id, map){
// set up CSS classes for inStock and outOfStock
dojo.addClass(id, item.type[0]);
});
Target container
var wishlist = new dojo.dnd.Source("wishlistNode", {
accept: ["inStock","outOfStock"]
});
here what I am doing;
dojo.connect(dojo.byId('JsonBtn'), 'onclick', function() {
var catalogNode = document.getElementById("catalogNode");
//Get all nodes in the assignRoleListContainer
var container2 = catalogNode.getAllNodes();
var results="";
var catalog_arr = [];
var len = container2.length;
for(var i=0;i<len;i++){
results = catalogNode.childNodes[i].childNodes[0].nodeValue;
catalog_arr.push(results);
}
//Json
var myJSON2 = "";
myJSON2 = JSON.stringify({catalog: catalog_arr});
});
I managed to convert all data in Json;
{"catalog":["Life jacket","Toy bulldozer","Wrist watch","Apples","Bananas","Bread","Tomatoes","Vintage microphone","TIE fighter"]}
But now I want to convert the items to json, but with respect to their types, e.g.
If type inStock
{"inStock":["Life jacket","Toy bulldozer","Wrist watch","Apples","Bananas","Bread"]}
If type outOfStock
{"outOfStock":["Tomatoes","Vintage microphone","TIE fighter"]}
Any suggestion?
Source container
var catalog = new dojo.dnd.Source("catalogNode", {
accept: ["inStock","outOfStock"]
});
catalog.insertNodes(false, [
{ data: "Wrist watch", type: ["inStock"] },
{ data: "Life jacket", type: ["inStock"] },
{ data: "Toy bulldozer", type: ["inStock"] },
{ data: "Vintage microphone", type: ["outOfStock"] },
{ data: "TIE fighter", type: ["outOfStock"] },
{ data: "Apples", type: ["inStock"] },
{ data: "Bananas", type: ["inStock"] },
{ data: "Tomatoes", type: ["outOfStock"] },
{ data: "Bread", type: ["inStock"] }
]);
catalog.forInItems(function(item, id, map){
// set up CSS classes for inStock and outOfStock
dojo.addClass(id, item.type[0]);
});
Target container
var wishlist = new dojo.dnd.Source("wishlistNode", {
accept: ["inStock","outOfStock"]
});
Button with Id=JsonBtn, and onClick event, convert data in target container to json
dojo.connect(dojo.byId('JsonBtn'), 'onclick', function() {
var target_container = wishlistNode.getAllNodes();
var inStock_arr = [];
var outOfStock_arr = [];
for(var i=0;i<target_container.length;i++){
if (hasClass("inStock", target_container[i].classList)){
var inStock_results = target_container[i].childNodes[0].nodeValue;
inStock_arr.push(inStock_results);
}
else if(hasClass("outOfStock", target_container[i].classList)){
var permissions_results = target_container[i].childNodes[0].nodeValue;
outOfStock_arr.push(outOfStock_results);
}
}
var result={};
result["inStock"]=inStock_arr;
result["outOfStock"]=outOfStock_arr;
alert(JSON.stringify(result));
});
Check classList function
function hasClass(className, classList){
for (var i=0; i<classList.length; i++){
if(classList[i]==className){
return true;
}
}
return false;
}
Output: (This output also fine for me)
{
"inStock":[
"Wrist watch", "Life jacket", "Toy bulldozer", "Apples", "Bananas", "Bread"],
"outOfStock":[
"Vintage microphone", "TIE fighter", "Tomatoes"]
}
First of all, thanks to FireFox team for their "FireBug". It helps a lot in debugging and programming and without it its very difficult for me to find the solution.
And if there any explanation needed, I am happy to help.

Categories