How to pass a string array as a JSON argument - c#

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 []

Related

C# - Jquery : Pass regular params and list<KeyPairValue<string, string>> with $.post from view to controller

I try to pass 'regular' parameters type from an ajax call ($.post) from a view to a controller which is supposed to receive those parameters plus a List>.
I need this List cause those parameters will be different from model.types, and the method in the controller dispatch all params in a switch case to private methods.
I tried several jquery objects builds, JSON.stringify, the array with indexes in the string (I know I can't name columns explicitly... part of my question) which always ends in the List> to null in the backend method.
The 'params' are visible in xhr debug, but the parameter _options is always null (ref controller method).
Here is my vars and my ajax call :
function initDocumentsPreviewsActions() {
$('.documents-list-preview-action').on('click', function () {
if (xhrPreviewLoad != undefined)
xhrPreviewLoad.abort();
$('#documents-preview').html('<div class="general-form-message-loader"></div>');
documentCurrentIndex = $(this).data('btnindex');
setDatatableRowActive();
var documentType = $(this).data('documenttype');
var adherentRessourceId = $(this).data('adherentressourceid');
var annee = $(this).data('annee');
var echeancier = $(this).data('echeancier');
var destinataireid = $(this).data('destinataireid');
var destinatairetypeid = $(this).data('destinatairetypeid');
var emetteurid = $(this).data('emetteurid');
var emetteurmandatid = $(this).data('emetteurmandatid');
var trimestres = $(this).data('trimestres');
var params = [
{ '_annee': '' + annee + '', '_echeancier': '' + echeancier + '', '_trimestres': '' + trimestres + '' }
];
xhrPreviewLoad = $.ajax({
url: '/Documents/PreviewDocumentSingle',
data: {
_documentType: documentType,
_adherentRessourceId: adherentRessourceId,
_annee: annee,
_destinataireId: destinataireid,
_destinataireType: destinatairetypeid,
_emetteurId: emetteurid,
_emetteurMandatId: emetteurmandatid,
_echeancier: echeancier,
_options: JSON.stringify(params)
},
dataType: 'json',
type: 'POST'
}).done(function (documentPartialView) {
$('#documents-preview').html('<img src="' + documentPartialView.src + '"/>');
xhrPreviewLoad = undefined;
});
});
}
xhd Parameters in Firefox debugger :
_documentType AppelCotisation
_adherentRessourceId 836
_annee 2018
_destinataireId 11
_destinataireType Syndicat
_emetteurId 16289
_emetteurMandatId 5986
_echeancier False
_options [{"_annee":"2018","_echeancier":"False","_trimestres":"undefined"}]
Controller method :
[HttpPost]
public JsonResult PreviewDocumentSingle(string _documentType, int _adherentRessourceId, int _destinataireId, string _destinataireType, int _emetteurId, int _emetteurMandatId, List<KeyValuePair<string, string>> _options)
{
//(_options = null)
//some code
return JsonResult
}
I already have done this a long time ago but I cannot put a hand or my brain on it. I'm sure it's a little thing.
I expect to get ALL my parameters correctly or being suggested to declare another List of a different type in the backend (and how to formalize it in front), or Array... well... any help is good to come.
But I'd really like to keep mus ctor in the backend as it is.
I finally findout myself how to solve this simple problem by changing to a Dictionnaray instead of a List> in my controller's method parameters and build a simple js object like this :
var options = {};
options['_annee'] = annee;
options['_echeancier'] = echeancier;
options['_trimestres'] = trimestres;

jquery how to get data from this array

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 :)

Retrieving data from a List<T> and putting it in a dropdown list using Jquery

I have retrieved data from the database and put it in a List. I need to access this list of items using Jquery and put them in a dropdown list. Here is my code in the Controller
//filling list with data from data reader
List<Object> list=new List<Object>();
while (read.Read())
{
var var1 = (int)read["dbColumn"];
var var2 = (string)read["dbColumn2"];
list.Add(var1);
list.Add(var2);
}
var serializer=new System.Web.Script.Serialization.JavaScriptSerializer();
string theData = serializer.Serialize(list);
return theData;
In my jquery I have this
if (!$.isEmptyObject(data))
{
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i].dbColumn];
var second = [data[i].dbColumn2];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html("<option>"+html+"</option>").show();
}
Then I have this as the Html code where I want the list to be displayed
<select id="SelectBox"></select>
When I try this, I get a looooooong list of empty option fields. What could be the issue
Don't wrap content of select control in <option>.
$('#SelectBox').html(html).show();
You are just returning a serialized List<Object> so there isn't a dbColumn1 or dbColumn2 in your result.
It might be worth creating a wrapper class or using a Dictionary<int, string> for your results but to make it work using your current code you can change your jQuery code to:
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i]];
var second = [data[++i]];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html(html).show();
Note that for the second value we are just incrementing i to get to the next item in the list. We are also just using the value from data[i] directly rather than trying to access any properties from it as it is just an array of items.
This gives a select box populated something like this:
Edit
It would seem from the comments that the Json being returned is not being parsed correctly as well as having your indexing and naming incorrect as per the above. Assuming you are using the jquery.ajax() method to retrieve the Json it is probably treating the returned item as a string. From the documentation on the dataType parameter (emphasis mine):
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
You could change your call to pass dataType: 'json' and as per the documentation jQuery will automatically parse it into a JavaScript object:
ajaxReq = $.ajax({
url: '/home/something',
dataType: 'json', //get jQuery to parse the response for us
success: function (data) {
//data is now a parsed JS object
var html = "";
var len = data.length;
for (var i = 0; i < len; i++) {
var first = [data[i]];
var second = [data[++i]];
html += '<option value=' + first + '>' + second + '</option>';
}
$('#SelectBox').html(html).show();
}
});
If you want to parse the json manually or you are using a different method to retrieve the results you could parse the json yourself by adding
data = JSON.parse(data);
before the line var len = data.length;
var batch= document.getElementById('id');
$(batch).append($("<option></option>").val(first ).html(second ));
Note :Id get using browser.ie(insepect element).

JSON returning object Object not String

The below code is returning [object Object] not a string. How can I get it to return the correct string representation? I am using ASP.NET MVC4 C#.
public JsonResult Names(string name)
{
var a = db.NamesToGet.Select(e => new
{
name = e.Names
});
return Json(a, JsonRequestBehavior.AllowGet);
}
try
var a = db.NamesToGet.Select(e=>e.Names);
Access it with data.name or substitute data to your json variable name.
$.get("/Controller/GetName", function(data) {
alert(data.name);
//or alert(data[0].name);
});

Access C# List inside Javascript

On the server side I create a list
List<object> data = new List<object>();
for (var j = 0; j < items.Count(); j++)
{
var temp = groups.Where(customfilter);
data.Add(Html.Raw(Json.Encode(temp)));
}
System.Web.Script.Serialization.JavaScriptSerializer serializer = new
System.Web.Script.Serialization.JavaScriptSerializer();
var serializedData = serializer.Serialize(data);
Inside Javascript the folowing won't work for anything but primitive types.
var localData = #data;
This is the error:
System.Collections.Generic.List`1[System.Object]
What am I missing?
I am assuming that the C# code you posted is a Controller action method.
You would need to have your controller method return a JsonResult, and then use a JSON library to deserialize it.
Something like
public class MyController: Controller
{
public JsonResult MyAction ()
{
var data = new List<object>();
for (var j = 0; j < items.Count(); j++)
{
var temp = groups.Where(customfilter);
data.Add(temp);
}
return Json (data, JsonRequestBehavior.AllowGet);
}
}
Note how you don't need to serialize every item as you add it to the list.
From the client side, you can call your method and deserialize the result to a list. You can do it like this:
$.ajax ({ url:'/My/MyAction'}).done (function (data) {
var myList = JSON.parse (data);
});
Edit:
After some testing, I found that you can access the data by doing:
var myList = data;
Not sure why, but "data" is sent directly as an array.
Hope it helps!
First of all check this link http://james.newtonking.com/pages/json-net.aspx
Second
var temp = groups.Where(customfilter).ToList();
If you use where cast it to list or it will be something like Query object *(I dont remember exactly type)
Or if you want to select one object try groups.FirstOrDefault
Third
data.Add(temp);
Serializer will do his job to convert it.

Categories