Read a JSON Serialized List<string> - c#

I have an ordinary List<string> that I convert to JSON with System.Web.Script.Serialization;
The result is something similar to this
[
"string1",
"string2",
"string3",
"string4",
"string5",
"string6"
]
Now how do I read this in jQuery? I prefer to be able to loop them out one by one.
Or am I supposed to make a better JSON object and return that, if so are there any good ways to make a JSON object from a List<string>?

Use an AJAX request in order to get the List to the client and the assign it to a JavaScript Array object:
var list = new Array();
$.ajax({
url: myUrl,
success: function(data){
list = data;
}
});
You can next iterate the list in order to access each element, either with jQuery ($.each), or with regular JavaScript:
for (var i = 0; i < list.length; i++){
//do whatever with *list[i]*
}

You can read it by looping it using $.each
$.each(yourList, function (index, value) {
console.log(index, value);
});

Related

Javascript function call to c# method to get array of integers for datatables.net column order

I must profess that i am not very good with Javascript.
I am creating a table using datatables.net
The datatable is populated using a call to a generic handler that will then call the database (in c#) to get values. This is working.
What i'd like to do is use the column re-order functionality. Setting the order is by an array of integers. I'd like those values to be stored in the database and then assign use it. I haven't thought about the saving columns order part first as i want to get the "get" process working first.
In a normal world, the code to set the column re-order is by coding it into the datatables functionlity like:
<script>
$(function () {
var columnOrder = [4, 3, 2, 1, 0, 5];
$("#<%=DT.ClientID%>").dataTable({
dom: 'Rlfrtip',
colReorder: {
order: columnOrder
},
"bProcessing": true,
"bServerSide": true,
"bFilter": false, //Hide the search box
"sPaginationType": "full_numbers",
"sAjaxSource": "../DataHandler/Data.ashx",
So what I'd like to do is to populate the "columnOrder" with values from the database.
i tried using a webmethod and then getting that value by $.ajax({ + Post. This went to my c# code behind method on the default.aspx but returned an empty object. It also seems to populate the datatable first before going into the webmethod so the timing of the call is not correct as well.
QUESTION: I'm scratching my head if I am over-complicating this. All i want is the return an array of integers from a c# server-side method to a javascript variable. Then use this variable to set the order of the column.
Any suggestion on how i can just get an array of integers from c# into a variable is basically what i'd need to get started.
thanks!
All i want is the return an array of integers from a c# server-side method to a javascript variable.
I have a method that return an array of integers, not really an array but it works like one in javascript.
The method is below
[WebMethod]
public static List<int> getAdd_Zip(int ZIP_ID)
{
try
{
BusinessContacts objContacts = new BusinessContacts();
DataTable dtInf = objContacts.getAdd_Zip(ZIP_ID);
List<int> lRes = new List<int>();
if (dtInf.Rows.Count > 0)
{
lRes.Add(Convert.ToInt32(dtInf.Rows[0]["COU_ID"]));
lRes.Add(Convert.ToInt32(dtInf.Rows[0]["STE_ID"]));
lRes.Add(Convert.ToInt32(dtInf.Rows[0]["MUN_ID"]));
}
return lRes;
}
catch (Exception ex)
{
throw ex;
}
}
Note that the method returns a List of integer, I declare a datatable, then I fill that table with another method (this not important), then, I fill the List with 3 values.
So now, I have the next method on javascript
function wsGetAdd_Zip(ZIP_ID) {
var AddZips = new Array();
var params = new Object();
params.ZIP_ID = ZIP_ID;
params = JSON.stringify(params);
$.ajax({
type: "POST",
url: "Contactos.aspx/getAdd_Zip",
data: params,
contentType: "application/json; charset=utf-8",
async: false,
success: function (result) {
AddZips = result.d;
},
error: function (XMLHttpRequest, textStatus, errorThrown) {
alert(textStatus + ": " + XMLHttpRequest.responseText);
}
});
return AddZips;
}
That method returns the array of integers.
I hope this helps you.

reading JSON data from aspx web form

I have an Regular ASP.Net web form (not a web service) that I'm trying to spit out JSON data which I'm then trying to consume. I have a 2 part question.
The 1st one is dealing with outputting the JSON data:
var reader2 = command.ExecuteReader();
while (reader2.Read())
{
var json = Json.Encode(new{
code = reader2[1].ToString(),
Revenue = reader2[4].ToString()
});
Response.Write(json);
}
reader2 contains 238 different entries. Right now the above Response.Write(json) returns 238 separate json strings:
{"code":"123","Revenue":"90.0000"}{"code":"234","Revenue":"90.0000"}
I think it might be helpful later (for question 2) if I had them grouped into 1 recordset.
{ "records": [ { "code":"123" , "Revenue":"90.0000" }, {
"code":"234" , "Revenue":"90.0000" } ] }
How would I do that with the above snippet using the reader and the System.Web.Helpers.Json?
The second question might be a direct result of how I'm currently outputting the JSON data from the first question. Ultimately I want to be able to read what ever I output from question 1 using this function. Right now my I set my dataType: "html" as that is the only thing I could get to return anything. However, that gives me a length for my msg of 32000+... Something isn't right.
What do I have to do to be able to read the JSON data output from my ASPX page?
function populateResults(code, district, year) {
$.ajax({
type: "GET",
url: "regular.aspx",
data: "code=" + code + "year=" + year,
dataType: "html",
success: function (msg) {
var results = msg;
$.each(results, function (index, result) {
console.log(result.code);
});
}
});
Re-reading the question after my comment, it's a little more clear now that "32000" isn't too much data in general, it's just that the data is being treated as one big string instead of as an array of objects.
This is probably because the data type is HTML, which is probably necessary because it's not seeing the response as correctly formatted JSON. I think you're right that it needs to be "grouped" though it might not need to be wrapped in a parent object like that. Try prepending with a [, appending with a ], and separating each with a comma. Maybe something like this:
var reader2 = command.ExecuteReader();
Response.Write("[");
var firstRecord = true;
while (reader2.Read())
{
if (!firstRecord)
Response.Write(",");
firstRecord = false;
var json = Json.Encode(new{
code = reader2[1].ToString(),
Revenue = reader2[4].ToString()
});
Response.Write(json);
}
Response.Write("]");
I had to throw in a little logic there to determine when to include a comma, since you don't want one before the first record or after the last record. There may be a more elegant way to do that, especially if you know the count coming from reader2. But hopefully you get the idea.
This should result in something more like this:
[{"code":"123","Revenue":"90.0000"},{"code":"234","Revenue":"90.0000"}]
Which by itself should be interpretable as JSON by the browser. This should allow you to set the data type:
dataType: "json"
Which should, in turn, give you what you're looking for in msg.
Edit: You may be able to simplify this a little more by turning the output from reader2 into an enumeration of objects and just using Json.Encode() on that whole thing. Maybe something like:
var records = new List<CustomRecord>();
while (reader2.Read())
{
records.Add(new CustomRecord {
code = reader2[1].ToString(),
Revenue = reader2[4].ToString()
});
}
Response.Write(Json.Encode(records));
And have a simple custom object:
class CustomRecord
{
public string code { get; set; }
public string Revenue { get; set; }
}

Send data from ajax to c# server

I've created a dictionary on cliend side and want to send it on sever side. In my script, dictionary is created correctly, but I'm not sure abount my ajax code.
$("#btnSubmit").click(function () {
var sendList = new Array();
var elems = $(".elemValue");
$.each(elems, function (key, value) {
if (value.attributes.elemName.nodeValue != "PhotoImg") {
sendList[value.attributes.elemName.nodeValue] = value.attributes.value.nodeValue;
}
});
var data = JSON.stringify({dict : sendList});
$.ajax({
type: "GET",
url: "dataloader.aspx/GetData",
data: data,
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (result){
alert(result.d);
}
});
});
On server side I wrote
[System.Web.Services.WebMethod]
public static string GetData(Dictionary<string,string> dict)
{
Dictionary<string, string> serverDict = new Dictionary<string, string>();
serverDict = dict;
string result = "";
foreach (var value in dict)
{
result += "The key is:" + value.Key + "The value is:" + value.Value;
}
return result;
}
Where are my mistakes, and how can I fix them? Help, please=)
I don't think it's possible to create a Dictionary from JSON. At least not without a lot of work. I would try changing it from a Dictionary to a List<KeyValuePair<string,string>> and see if it deserializes for you.
Reference for KeyValuePair
Once you've done that if you still need the Dictionary you can convert it fairly easily.
var Dictionary = new Dictionary<string,string>();
foreach(var KVP in List) Dictionary.Add(KVP.Key, KVP.Value);
Couple of things here:
You need to allow GET verb explicitly:
[System.Web.Services.WebMethod]
[System.Web.Script.Services.ScriptMethod(UseHttpGet=true)]
You are returning plain text from the server, which means that this line:
dataType: "json"
won't let jQuery parse the response correctly. You should either remove this line, or build response in JSON format.

Array Passed to Controller Received as NULL

I'm using $.post() to post an array of integer values to my controller.
Here's how I construct my array:
var ratings = [];
$('#ratings input[name=newReviewRatings]').each(function () {
ratings.push($(this).val());
});
Here's how I'm posting it to the controller:
$.post('#Url.Action("CreateReview", "Provider")',
{
id: providerId,
ratings: ratings,
comment: comment
});
Here's the form data that gets posted:
{id=437baf29-4196-4966-88de-a8fde87ef68d&ratings%5b%5d=1&ratings%5b%5d=2&ratings%5b%5d=3&ratings%5b%5d=4&ratings%5b%5d=5&comment=Comments}
And here's my controller signature:
public ActionResult CreateReview(Guid id, int[] ratings, string comment)
{
// ....
}
That seems like that should be right, but ratings is always null. Can anyone see what I'm missing?
I also tried string[] ratings and got the same result. I also saw a suggestion to pass the array using JSON.stringify(ratings) but that didn't seem to help either.
In adition to converting the post data to json, you can also set the traditional param to true. This will cause jQuery to use the correct post format for MVC.
jQuery.ajaxSettings.traditional = true;
$.post('#Url.Action("CreateReview", "Home")',
{
id: 'GUID STRING HERE',
ratings: [1, 2, 3],
comment: 'adfef'
});
Try to specify contentType like this:
$.ajax({
url:url,
type:"POST",
data:data,
contentType:"application/json; charset=utf-8",
dataType:"json",
success: function(){
...
}
})

value not passing

I'm trying to send selected checkbox values to another asp page to update database.
$("#Delete_selected_Comment_button").click(function () {
var dataToBeDeleted = new Array();
$('.checkboxes_to_delete:checked').each(function (key, value) {
dataToBeDeleted .push($(this).val());
});
$.ajax({
url: 'http://myurl.aspx',
type: 'GET',
data: dataToBeDeleted,
success: function () { alert('yipee'); },
error: function () { alert("Ooff could not delete data"); }
});
});
Problem:
I am not able to retrieve any value in myurl.asp page.
I am doing:
String datagotfromajax= request.QueryString[dataToBeDeleted];
Am doing this incorrectly? Where is my mistake ? Can anyone help please?
An easy way would be to change one line:
data: "ids="+dataToBeDeleted.join(","),
And, in the server do:
string[] ids = Request.QueryString["ids"].ToString().Split(",");
With this you'll hava a string array in the server with the corresponding checkboxes values.
HOpe this helps.
dataToBeDeleted will be converted to a query string (if its not already) when sent to the server, that means it consists key-value pairs, i.e. foo=bar&fred=fish. On the server you can query individual key-value pairs using the syntax
string bar = request.QueryString["foo"];
You are passing an array as the data parameter. This won't work. You need to pass an object. If the object contains an array, this will be serialized appropriately. This means your code should probably look like this:
data: {
toBeDeleted: dataToBeDeleted
},
This will then be serialized appropriately (see $.param for the serialization process) and you can retrieve the values with your back-end code.

Categories

Resources