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 :)
i'd like to better understand the issue of casting object to a name vs value collection
say ...just if i could do it like that
1) does the java-script needs some fine tuning ? packing the data..
2) and most important for me : What is the correct way to do the conversion from that key value Js to a Dictionary<T,T> C# ?
the Aspx / Html part
<input type="text" id="tbx_Name" value="Avi" />
<input type="text" id="tbx_City" value="TelAviv" />
<input type="text" id="tbx_Country" value="Israel" />
<select id="ChosenRandomClass" style="display:none">
<option selected="selected" value="0">(choose a random)</option>
<option value="1">random Top Beach</option>
<option value="2">random Top Center</option>
<option value="3">random Local Pub</option>
</select>
the JavaScript / jQuery part
function AddNew() {
if (!confirm("would you like to add this contact ?")) return;
var Name = $('#tbx_Name').val();
var City = $('#tbx_City').val();
var Country = $('#tbx_Country').val();
var selectedRC = $('#ChosenRandomClass option:selected').val();
var hDate = []
var param1 = { key: "Name", value: Name };
var param2 = { key: "City", value: City };
var param3 = { key: "Country", value: Country };
var param4 = { key: "SelctedClass", value: selectedRC };
hDate.push(param1);
hDate.push(param2);
hDate.push(param3);
hDate.push(param4);
// is this part necessary the data will not get to
// code behind properly without the serializing ?
var startPrt = Sys.Serialization.JavaScriptSerializer.serialize(hDate);
ajaxUpdate("addNew", startPrt);
}
the Code behind C# part
public void AddNewRecord(object startPrt)
{
Dictionary<string, string> SenthDate = new Dictionary<string, string>();
// .....etc
}
i will appreciate the correct answer
thanks for your kind help and time.
I gave your sample a try and noticed that the startPrt parameter is actually being received as an Array of Dictionary(string, object). Hence, if you make the AJAX call like this:
var hDate = [];
hDate.push({ key: "Name", value: Name });
hDate.push({ key: "City", value: City });
hDate.push({ key: "Country", value: Country });
hDate.push({ key: "SelctedClass", value: selectedRC });
$.ajax({
contentType: 'application/json; charset=utf-8',
url: 'MyPage.aspx/AddNewRecord',
type: 'POST',
data: JSON.stringify({ startPrt: hDate }),
success: success, // success callback
error: error // error callback
});
You can define your WebMethod like the follwoing to convert the startPrt parameter to a dictionary:
[WebMethod]
public static void AddNewRecord(object startPrt)
{
var dict = new Dictionary<string, object>();
foreach (Dictionary<string, object> pair in (Array)startPrt)
dict.Add((string)pair["key"], pair["value"]);
}
The conventional approach would be to construct a plain javascript object, which can be used by jQuery.ajax(...) without any pre-processing.
var hDate = {
"Name": $('#tbx_Name').val(),
"City": $('#tbx_City').val(),
"Country": $('#tbx_Country').val(),
"SelctedClass": $('#ChosenRandomClass').val()
};
ajaxUpdate("addNew", hDate);
In ajaxUpdate(), the ajax expression will be something like this :
function ajaxUpdate(action, data) {
...
$.ajax({
url: '...',
data: data,
...
success: function(){
...
}
});
}
Thus the serialized data will made available to the server-side script of whatever flavour.
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'
}
}
});