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; }
}
Related
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.
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);
});
UPDATE: This code now works! Between the answer below and my dev who emailed me from Romania, I got it sorted out.
[Method]
public object ConvDetails(string SENDERNAME, string VIEWURL)
{
{
var list = new List<object>();
new Command("select top 1 o.name [SENDERNAME], view_url [VIEWURL] from MESSAGE m join OPR_SECD o on UPDATED_BY = O.RECNUM where VIEW_URL like 'conversation.aspx%' and DELIVER_TO in (select OPR_INITIAL from OPR_SECD where recnum = #CURRENT_USER_ID) order by m.RECNUM desc")
.AddInt("CURRENT_USER_ID", Common.UserID)
.Each(R => list.Add(new
{
VIEWURL = R.GetString("VIEWURL"),
SENDERNAME = R.GetString("SENDERNAME")
}));
return list;
};
}
Here's my ajax call to get the two strings from my method:
convDetails: function() {
$.ajax({
url: BASE_URL + "pages/services/messages.ashx?method=convdetails",
dataType: "json",
async: true,
data: {},
success: function(data) {
$("a.new-message-alert").attr("href", '' + data[0].VIEWURL);
$("span#message-from").text("New Message From: " + data[0].SENDERNAME);
}
});
}
UPDATE:
Between the response I got below and a few emails to our developer who's in Romania, I was able to piece it together. I updated my code to what worked! The having just data.VIEWURL didn't work. I had to add the data[0].VIEWURL. So, thanks Matt for that one. Also, in my href i had to put in empty quotes or it would return NaN. No idea why.
Thanks!
Well, that JavaScript isn't going to work whatever you do on the C# side. You're attempting synchronous processing of the result of an asynchronous call.
Your C# doesn't look far off, for some reason I totally failed to read it correctly first time around. I've never used a .ashx in quite that manner, I've always just spat out my response from ProcessRequest, but if your code is getting called then I just learned something new. I do, however, notice that you're returning a serialized list, but only processing one element.
You could use a more LINQy approach to eliminate the explicit list filling, though:
var list =
from R in new Command("select top 1 o.name [SENDERNAME], view_url [VIEWURL] from MESSAGE m join OPR_SECD o on UPDATED_BY = O.RECNUM where VIEW_URL like 'conversation.aspx%' and DELIVER_TO in (select OPR_INITIAL from OPR_SECD where recnum = #CURRENT_USER_ID) order by m.RECNUM desc")
.AddInt("CURRENT_USER_ID", Common.UserID)
select new {
VIEWURL = R.GetString("VIEWURL"),
SENDERNAME = R.GetString("SENDERNAME") };
context.Response.Write(JsonConverter.SeralizeObject(list));
Your JS should look more like:
convDetails: function() {
$.ajax({
url: BASE_URL + "pages/services/messages.ashx?method=convdetails",
async: true,
data: {},
success: function(data) {
$("a.new-message-alert").attr("href", data[0].VIEWURL);
$("a.new-message-alert").text("New message from: " + data[0].SENDERNAME);
}
});
}
--I've deleted the original text to try to clean the post up a bit--
--------EDIT-------------------------------------------------------------------------
Here is some more info not sure if it helps anyone that's ran into this issue before.
Here is what my final object looks like in the JS script:
var DealerModel = {
Dealer: {
AccountId: 5678,
Name: "Austin",
City: "Who knows",
State: "TN"
},
Test: 111,
DealerCategories: [{Name: "Test1", Value:"Value1"},{Name:"Test2", Value:"Value2"}]
}
When I pass this into my controller via jquery it has the 111 value for Test, it shows that DealerCategories has 2 objects, but for both those objects as well as Dealer it shows NULL.
I've changed up the model/controller a few times and it seems no matter what if I pass in an object that has a sub json object it doesn't like that. I have a feeling this is something simple i'm missing.
the model binder knows how to bind arrays from JSON so you just have to give him something like this :
var DealerModel =
{
Dealer : 'my_dealer_value_here',
DealerContact = [] <- a list of Contrats here
}
and i think this should do it.
If your issue is with taking the leap from posting simple values like strings and numbers through jQuery.post, you can also provide json objects, like the one listed by Alex, above.
$.ajax({
type: "POST",
url: 'MYURL',
data: {
Dealer : {id:-1, accountId: '', name:'TheDealer'},
DealerContact: [{FirstName:'ContactName',...},{...},...]
}
});
And that bit of data should deserialize to your objects.
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.