jquery how to get data from this array - c#

This is my c# code:
Dictionary<string, double[][]> dictionary = new Dictionary<string, double[][]>();
dictionary.Add("ServiceLevel", finalArray);
dictionary.Add("NumberOfCalls", numberOfCallsArray);
Where finalArray and numberOfCallsArray is double[][] full of data.
I send it to jquery like this:
string jsonformatstring = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(jsonformatstring);
HttpContext.Current.Response.End();
Then in jquery after doing a json request and get the data successfully. I do this:
var data = $.map(result, function (arr, key) {
return { label: key, data: arr };
});
console.log(data["ServiceLevel"] + "--");
My problem
I got undefined in the console when I tried this: console.log(data["ServiceLevel"] + "--");
Maybe I am getting the value in the wrong way?
Update 1
I did this:
console.log(result);
and I got this
Update 2
I tried this:
var s = JSON.stringify(result); console.log(s)
The result is this:
{"ServiceLevel":[[1390608000000,50],[1392595200000,0],[1393286400000,66.66666666666667],[1393891200000,50],[1394064000000,0],[1394236800000,50],[1394323200000,0],[1394841600000,50],[1394928000000,33.333333],[1395014400000,0],[1395100800000,50],[1395273600000,0],[1395446400000,0],[1395619200000,0],[1395705600000,0],[1395878400000,50],[1396310400000,50],[1396483200000,0],[1396656000000,0],[1396828800000,50],[1396915200000,50],[1397001600000,50],[1397347200000,33.333333],[1397433600000,50],[1397952000000,0],[1398124800000,50],[1398556800000,0],[1398902400000,45],[1399075200000,0],[1399161600000,0],[1399334400000,0],[1399420800000,50],[1399680000000,0],[1399852800000,50],[1399939200000,0],[1400025600000,0],[1400112000000,33.333333],[1400284800000,40],[1400371200000,0],[1400457600000,50],[1400716800000,40],[1402185600000,50],[1402358400000,50],[1402531200000,0],[1402704000000,44.117647],[1402876800000,50],[1403308800000,50],[1403481600000,50],[1403913600000,0],[1407283200000,0],[1390780800000,100],[1391040000000,100],[1391558400000,100],[1392249600000,100],[1392681600000,75],[1392854400000,100],[1396137600000,100],[1397260800000,100],[1399507200000,100],[1400889600000,88.888888],[1401840000000,100],[1403654400000,100],[1407369600000,70.83333300000001],[1407628800000,100],[1408060800000,100],[1408233600000,50],[1408320000000,0]],"NumberOfCalls":[[1390608000000,50],[1392595200000,2],[1393286400000,14],[1393891200000,7],[1394064000000,1],[1394236800000,36],[1394323200000,3],[1394841600000,10],[1394928000000,11],[1395014400000,2],[1395100800000,45],[1395273600000,24],[1395446400000,13],[1395619200000,11],[1395705600000,11],[1395878400000,3],[1396310400000,18],[1396483200000,44],[1396656000000,2],[1396828800000,4],[1396915200000,25],[1397001600000,3],[1397347200000,11],[1397433600000,10],[1397952000000,15],[1398124800000,18],[1398556800000,1],[1398902400000,13],[1399075200000,2],[1399161600000,2],[1399334400000,1],[1399420800000,16],[1399680000000,3],[1399852800000,19],[1399939200000,32],[1400025600000,1],[1400112000000,20],[1400284800000,6],[1400371200000,3],[1400457600000,9],[1400716800000,12],[1402185600000,21],[1402358400000,14],[1402531200000,4],[1402704000000,37],[1402876800000,13],[1403308800000,18],[1403481600000,2],[1403913600000,1],[1407283200000,2],[1390780800000,2],[1391040000000,6],[1391558400000,6],[1392249600000,5],[1392681600000,6],[1392854400000,1],[1396137600000,2],[1397260800000,2],[1399507200000,1],[1400889600000,18],[1401840000000,6],[1403654400000,3],[1407369600000,16]

Your input is not clear, so i am assuming you got data something like
var result = {"ServiceLevel":[[1390608000000,50],[1392595200000,0]],
"NumberOfCalls":[[12,10],[100,0]]};
var arr = $.map(result, function (arr, key) {
return { label: key, data: arr }; });
Converting to Array:
var arr = $.map(result, function (arr, key) {
return { label: key, data: arr };
});
Reading Elements:
element at position 1:
arr[0].data[0][1] is 1
element at position 3:
arr[0].data[2][2] is 3
to get key use:
arr[0].label , it will give you "ServiceLevel"
arr[1].label , it will give you "NumberOfCalls"

var data = $.map(result, function (arr, key) {
return { label: key, data: arr };
});
You're returning an associative array with "label" and "data" elements. data["data"] should contain what you're looking for.
If you did:
$.map(result, function (arr, key) {
console.log(arr["ServiceLevel"] + "--");
return { label: key, data: arr };
});
you'd see it being returned. it's just because you've wrapped your "data" in another array.

I believe you're getting undefined because you didn't parse the json you received from your c# code.
I had this problem too, the thing is this :
string jsonformatstring = JsonConvert.SerializeObject(dictionary, Formatting.Indented);
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ContentType = "application/json; charset=utf-8";
HttpContext.Current.Response.Write(jsonformatstring);
HttpContext.Current.Response.End();
returns a String. To be used as Json you need to parse it, JsonConvert.SerializeObject only format the object into {[ key:value ]}.
here's a sample of an ajax success function i made with json :
success: function (data) {//on success
var results = JSON.parse(data); //parse result to work on it
$.each(results, function (index, element) {
//do something
});
I don't know how you retrieve your Json string but try parsing it before working on it :)

Related

Deserialize from json string to list of dictionary?

I am passing array of json objects from ajax method.
var FieldValue = {
Key: $(this).attr("id"),
Value: $(this).val()
};
FieldValues.push(FieldValue);
$.ajax({
url: "../Handler.ashx?&Action=Save",
data: JSON.stringify(FieldValues),
type: "post",
datatype: "json",
contentType: "application/json; charset=utf-8",
});
But when i tried to deserialize to List of dictionary.
JavaScriptSerializer javaScriptSerializer = new JavaScriptSerializer();
List<Dictionary<string, string>> WebFields = new List<Dictionary<string, string>>();
WebFields = javaScriptSerializer.Deserialize<List<Dictionary<string, string>>>(jsonString);
My expected output list is like,
string Key = WebFields[0].Key
string Value = WebFields[0].Value
But now it is like each WebField item is like,
WebFields[0] -> [0] -> Key
[1] -> Value
How to achieve my expected output ?
To get a dictionary server side, try to send a basic POJO.
Instead of:
var FieldValue = {
Key: $(this).attr("id"),
Value: $(this).val()
};
FieldValues.push(FieldValue);
try:
var key = $(this).attr("id");
var value =$(this).val()
var fieldValue = { key: value };
fieldValues.push(fieldValue);
A javascript object is represented as a key value pair, thus returning a Dictionary will return a JS object with the key being propname, and value being the value

Ajax call to action with a List of KeyValuePairs as parameter

I wish to simply do an AJAX call to a method expecting a List of Key and value pairs, but I have no idea how to do this. I tried the following:
Server method:
UpdateBranches(List<KeyValuePair<string, string>> brancheItems)
data to be send:
var brancheItems = [];
businessActivities.forEach(f =>
brancheItems.push({
Key: f.sbiCode,
Value: f.sbiCodeDescription
})
This seemed to give me an array of objects with key and value properties. (network tab showed it), but it did not work. I also tried to make an array of objects with one property (propertyname is the key, value is the value):
for (var itemIndex in items[index].businessActivities) {
var key = items[index].businessActivities[itemIndex].sbiCode;
brancheItems.push({
key: items[index].businessActivities[itemIndex].sbiCodeDescription
});
}
Note that on the server I seem to receive an array/list of 3 items with two properties, but the properties are always empty. Does anyone know the correct format for the data to be send
I think you can simply create your object like this:
var ParamtersContainer = new Object();
ParamtersContainer = {
"PatientName": 'Alameer',
"ServiceDate": '12/12/2017',
"ProviderName": 'ahmed'
};
Then make it as data parameter in your ajax request, receive it as a dictionary in your c# action.
Use something like this.
$.ajax({
type: 'POST',
url: url,
contentType: "application/json",
data:JSON.stringify( {brancheItems: brancheItems}),
success: function (data) {
alert("Succeded");
}
});
And use the bracket notation:
Instead of brancheItems.push({ key : value });
use
var object = {};
object[key] = value;
brancheItems.push(object);

Ajax call is passing controller name and method name instead of data

I am running into some trouble with my ajax call. Here is the controller code:
[Route("RatingInfo/HandleRequest")]
[HttpPost]
public ActionResult HandleRequest(Dictionary<string, string> textBoxValues)
{
var result = CreateJson(textBoxValues); // This is a simplified example
return Json(result);
}
And here is my Jquery/ajax (Razor syntax):
function PassData () {
var data = {};
$('.divCell input').each(function (index, item) {
var id = $(item).attr('id');
var value = item.value;
data['dictionary[' + index + '].Key'] = id;
data['dictionary[' + index + '].Value'] = value;
});
$.ajax({
url: '#Url.Action("HandleRequest")',
type: 'POST',
dataType: 'JSON',
traditional: true,
data: data,
sucesss: function (result) {
alert('Success');
}
})
}
The idea here is to get the data from each textbox and pass it back to the server as a Dictionary with the id as the key and value as, well, the value.
Stepping through the Chrome debugger, the JS data object is built successfully.
From the debugger:
Local
data: Object
dictionary[0].Key: "Address"
dictionary[0].Value: "123 Main St"
dictionary[1].Key: "ZipCode"
dictionary[1].Value: "99999"
dictionary[2].Key: "Phone1"
dictionary[2].Value: "(555) 555-5555"
...
__proto__: Object
However, when the data is passed back to the controller, the values inside textBoxValues does not contain the passed data. Rather, it contains two key/value pairs with keys controller and action and values the names of the controller and action.
From the Visual Studio debugger:
textBoxValues = Count = 2
[0] = {[controller, RatingInfo]}
[1] = {[action, HandleRequest]}
How can I get Jquery to pass the data rather than the controller/action names? I am confused as to how this can even happen in the first place. Any help would be appreciated.
UPDATE
Sorry, I had put wrong code in.
The reason why this was not working is because the name of the parameter was incorrect, giving you a mismatch.
The below will work for you. Notice the name of dictionary is changed to your parameter textBoxValues:
function PassData() {
var data = {};
$('.divCell input').each(function (index, item) {
var id = $(item).attr('id');
var value = item.value;
data['textBoxValues[' + index + '].Key'] = id;
data['textBoxValues[' + index + '].Value'] = value;
});
$.ajax({
url: '#Url.Action("HandleRequest")',
type: 'POST',
traditional: true,
data: data,
sucesss: function (result) {
alert('Success');
}
})
}

How to pass a string array as a JSON argument

I'm trying to pass a couple of arguments to my JSON callback, however the string[] argument remains null. How do I need to pass the string array from javascript to get this working?
Javscript function:
function jsonCallback(jsonCallbackID, argumentsArray) {
var argumentValues = [];
for (var i = 0; i < argumentsArray.length; i++) {
argumentValues.push('' + $("#" + argumentsArray[i]).val());
}
// build request
var url = encodeURI("/DataEntry/JsonCallback/");
var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: argumentValues, rndvalue: Math.floor(Math.random() * 10000000001) });
// fire request
$.getJSON(url, data, function (data) {});
The actual callback C# function:
public JsonResult JsonCallback(int jsonCallbackID, string[] jsonCallbackValues)
{ }
This function does get called however, argument 'jsonCallbackValues' is null.
EDIT
To get this working I did the following:
var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: argumentValues.toString(), rndvalue: Math.floor(Math.random() * 10000000001) });
And split the jsonCallbackValues string at "," to get the resulting array.
You can give a try to JSON API ...
var data = {
jsonCallbackID:jsonCallbackID,
jsonCallbackValues: JSON.stringify(argumentValues),
rndvalue: Math.floor(Math.random() * 10000000001)
};
// your
$.getJSON(url, data, function (data) {});
JSON is a serialized language, so you can't put objects inside.
You should build your array in JSON format:
jsonCallbackValues : ["value1", "value2"...]
Try like this
var data = ({ jsonCallbackID: jsonCallbackID, jsonCallbackValues: $.toJSON(argumentValues), rndvalue: Math.floor(Math.random() * 10000000001) });
I have used a JSON jQuery plugin from http://code.google.com/p/jquery-json/
In the controller method change it to
string jsonCallbackValuesArray
Then use
JavaScriptSerializer orJSON.Net
to convert the JSON string into String []

Store with json reader is not working

I have following json created after I sereliaze a dictionary
{"Results":["{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}"],"Total":4}
When I try to load it into the extjs store , the store is not loaded
var store = Ext.create('Ext.data.Store', {
fields: fields,
pageSize: itemsPerPage,
proxy: {
type: 'ajax',
url: getDataWithPageURL,
reader: {
type: 'json',
root: 'Results',
totalProperty: 'Total'
}
}
});
But if I remove slash hard coded and it's working
{"Results":["{"BaseCurrency":"USD","TermCurrency":"JPY"}","{"BaseCurrency":"USD","TermCurrency":"JPY"}","{"BaseCurrency":"USD","TermCurrency":"JPY"}","{"BaseCurrency":"USD"}"],"Total":4}
I create json using Newtonsoft.Json
Dictionary<string, object> dict = new Dictionary<string, object>();
string s = JsonConvert.SerializeObject(dist);
How can I remove slash in server side in order to produce valid json for extjs store.
I tried
result = result.Replace("\"","'");
And
result =result.Replace("\"", #"""")
It's not working
Clearly, Ext doesn't like that you have encoded a json object as a string and then put them in another json object. You have two options that I see.
See if you can return the dict on the server-side without first converting it into a string. Some code, somewhere, is taking your string and putting it in a json object with 'Results' and 'Total'. Check to see if that code can take a Dictionary as-is.
Unwrap the 'Results' propery on the client-side. One way would be to make your own reader:
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.my-json',
read: function(object) {
object.Results = Ext.Array.map(object.Results, Ext.decode);
return this.callParent([object]);
}
});
Then use type: 'my-json' in your reader config.
Here is my test case:
var data = {"Results":["{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}","{\"BaseCurrency\":\"USD\",\"TermCurrency\":\"JPY\"}"],"Total":4};
Ext.define('Currency', {
extend: 'Ext.data.Model',
fields: [
{ name: 'BaseCurrency', type: 'string' },
{ name: 'TermCurrency', type: 'string' }
]
});
Ext.define('MyReader', {
extend: 'Ext.data.reader.Json',
alias: 'reader.my-json',
read: function(object) {
object.Results = Ext.Array.map(object.Results, Ext.decode);
return this.callParent([object]);
}
});
var store = Ext.create('Ext.data.Store', {
model: 'Currency',
data: data,
proxy: {
type: 'memory',
reader: {
type: 'my-json',
root: 'Results',
totalProperty: 'Total'
}
}
});

Categories