473,406 Members | 2,894 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,406 software developers and data experts.

How to return JSON data from ASPX page?

ssnaik84
149 100+
Hello,

I am trying to integrate FlexBox
It uses JSON data to populate listbox items.
It internally calls a server side page with AJAX, and reads the JSON results from that page.

for example,
Expand|Select|Wrap|Line Numbers
  1.  $('#flexbox1').flexbox('flexbox-results.aspx');  
here, page "flexbox-results.aspx" needs to return JSON result.
when I use
Expand|Select|Wrap|Line Numbers
  1. Response.ContentType = "application/json";
  2. Response.Write(jsonResult);
it does not work..

Let me know how to proceed..
Thanks in Adv.
Swapnil
Dec 1 '09 #1

✓ answered by Frinavale

That article looks over complicated.

I don't know if web services or a server control is best for your situation...I've never used FlexBox before. Mind you, glancing over the document that you linked to suggests that maybe a web service could work...but the example shows it calling an aspx page.


Regardless of whether you're using an ASPX page or if you use a Web Service, I recommend that you create a class that matches the JSON class that the FelxBox is expecting. Make this class serializable and use the JavaScriptSerializer to create a JSON version of it.

It looks like there are 2 properties that the JSON Object needs: an "ID" and a "Name".

So in the ASPX page create a private class:
Expand|Select|Wrap|Line Numbers
  1. <Serializable()> Private class FlexBoxItem
  2.   Private _name As String
  3.   Private _id As Integer
  4.  
  5.   Public Property id As Integer
  6.     Get
  7.       return _id
  8.     End Get
  9.     Set (ByVal value As Integer)
  10.       _id = value
  11.     End Set
  12.   End Property
  13.  
  14.   Public Property name As String
  15.     Get
  16.       return _name
  17.     End Get
  18.     Set (ByVal value As String)
  19.       _name= value
  20.     End Set
  21.   End Property
  22. End Class
  23. Public Sub New(ByVal itemID As Integer, ByVal itemName As String)
  24.  Me._id = itemID
  25.  Me._name = itemName
  26. End Sub
  27.  
Now you need a collection of these List Items...and you have to serialize them into an Array of JSON "FlexBoxItems":
Expand|Select|Wrap|Line Numbers
  1. 'Populating list:
  2. myListOfFlexBoxItems.Add(New FlexBoxItem(1,"first item"))
  3. myListOfFlexBoxItems.Add(New FlexBoxItem(2,"second item"))
  4. myListOfFlexBoxItems.Add(New FlexBoxItem(3,"third item"))
  5.  
  6. 'Serializing list:
  7. Dim jss As New JavaScriptSerializer()
  8. Dim jsonFlexBoxItems As New StringBuilder
  9. jss.Serialize(myListOfFlexBoxItems, jsonFlexBoxItems)
  10.  
  11. 'Now send the jsonFlexBoxItems to the browser
  12. Response.ContentType = "application/json";
  13. Response.Write(jsonFlexBoxItems.ToString);
  14.  
Please note that I have not tested this code...it's just meant to give you an idea how to use the JavaScriptSerializer to send the array of JSON objects to the browser.

-Frinny

9 34985
Frinavale
9,735 Expert Mod 8TB
You need to serialize the content that you are sending to the page.

I've done this a few times with Web Services and once with Web Server Control but I'm not sure how you are going to integrate the two.

Check out the JavaScriptSerializer class.

-Frinny
Dec 1 '09 #2
ssnaik84
149 100+
Thanks Frinny..
Actually I was following an article, which has given the most simplest way to return JSON. here it is..

But, I failed to achieve the results.
Should I use Webservice? or is there any other easier way?
Dec 1 '09 #3
ssnaik84
149 100+
ok.. this is the code sample, I have tried..

Expand|Select|Wrap|Line Numbers
  1. protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.             DataTable dt = new DataTable();
  4.             dt.Columns.Add("Name");
  5.             dt.Columns.Add("Value");
  6.  
  7.             DataRow dr1 = dt.NewRow();
  8.             dr1["Name"] = "111";
  9.             dr1["Value"] = "abc";
  10.             dt.Rows.Add(dr1);
  11.  
  12.             DataRow dr2 = dt.NewRow();
  13.             dr2["Name"] = "222";
  14.             dr2["Value"] = "aaa";
  15.             dt.Rows.Add(dr2);
  16.  
  17.             DataRow dr3 = dt.NewRow();
  18.             dr3["Name"] = "333";
  19.             dr3["Value"] = "axx";
  20.             dt.Rows.Add(dr3);
  21.  
  22.             DataRow dr4 = dt.NewRow();
  23.             dr4["Name"] = "444";
  24.             dr4["Value"] = "bbb";
  25.             dt.Rows.Add(dr4);
  26.  
  27.  
  28.             //start json result
  29.             string jsonResult = "{'results':[";
  30.             jsonResult += "";
  31.  
  32.             int i = 0;
  33.             foreach (DataRow dr in dt.Rows)
  34.             {
  35.                 i++;
  36.                 jsonResult += "{'id':'" + dr["Name"].ToString() + "',";
  37.                 if (i < dt.Rows.Count)
  38.                 {
  39.                     jsonResult += "'name':'" + dr["Value"].ToString() + "'},";
  40.                 }
  41.                 else
  42.                 {
  43.                     jsonResult += "'name':'" + dr["Value"].ToString() + "'}";
  44.                 }
  45.  
  46.             }
  47.  
  48.             //end json string
  49.             jsonResult += "]}";
  50.  
  51.             //Response.Headers.Add("Content-type", "text/json");
  52.             //Response.Headers.Add("Content-type", "application/json");
  53.             Response.ContentType = "application/json";
  54.             Response.Write(jsonResult);
  55.  
  56.         }
  57.  
when I debugged, it's giving me JSON result string like..

Expand|Select|Wrap|Line Numbers
  1. {'results':[
  2. {'id':'111','name':'abc'},
  3. {'id':'222','name':'aaa'},
  4. {'id':'333','name':'axx'},
  5. {'id':'444','name':'bbb'}]}
Dec 1 '09 #4
Frinavale
9,735 Expert Mod 8TB
That article looks over complicated.

I don't know if web services or a server control is best for your situation...I've never used FlexBox before. Mind you, glancing over the document that you linked to suggests that maybe a web service could work...but the example shows it calling an aspx page.


Regardless of whether you're using an ASPX page or if you use a Web Service, I recommend that you create a class that matches the JSON class that the FelxBox is expecting. Make this class serializable and use the JavaScriptSerializer to create a JSON version of it.

It looks like there are 2 properties that the JSON Object needs: an "ID" and a "Name".

So in the ASPX page create a private class:
Expand|Select|Wrap|Line Numbers
  1. <Serializable()> Private class FlexBoxItem
  2.   Private _name As String
  3.   Private _id As Integer
  4.  
  5.   Public Property id As Integer
  6.     Get
  7.       return _id
  8.     End Get
  9.     Set (ByVal value As Integer)
  10.       _id = value
  11.     End Set
  12.   End Property
  13.  
  14.   Public Property name As String
  15.     Get
  16.       return _name
  17.     End Get
  18.     Set (ByVal value As String)
  19.       _name= value
  20.     End Set
  21.   End Property
  22. End Class
  23. Public Sub New(ByVal itemID As Integer, ByVal itemName As String)
  24.  Me._id = itemID
  25.  Me._name = itemName
  26. End Sub
  27.  
Now you need a collection of these List Items...and you have to serialize them into an Array of JSON "FlexBoxItems":
Expand|Select|Wrap|Line Numbers
  1. 'Populating list:
  2. myListOfFlexBoxItems.Add(New FlexBoxItem(1,"first item"))
  3. myListOfFlexBoxItems.Add(New FlexBoxItem(2,"second item"))
  4. myListOfFlexBoxItems.Add(New FlexBoxItem(3,"third item"))
  5.  
  6. 'Serializing list:
  7. Dim jss As New JavaScriptSerializer()
  8. Dim jsonFlexBoxItems As New StringBuilder
  9. jss.Serialize(myListOfFlexBoxItems, jsonFlexBoxItems)
  10.  
  11. 'Now send the jsonFlexBoxItems to the browser
  12. Response.ContentType = "application/json";
  13. Response.Write(jsonFlexBoxItems.ToString);
  14.  
Please note that I have not tested this code...it's just meant to give you an idea how to use the JavaScriptSerializer to send the array of JSON objects to the browser.

-Frinny
Dec 1 '09 #5
ssnaik84
149 100+
Thanks a lot for neat guidance.. I have tried in following way..

Expand|Select|Wrap|Line Numbers
  1. [Serializable()]
  2.     public class FlexBoxItem
  3.     {
  4.         string _id = string.Empty;
  5.         string _name = string.Empty;
  6.  
  7.         /// <summary>
  8.         /// get/set id of flex box item
  9.         /// </summary>
  10.         public string id
  11.         {
  12.             get { return _id; }
  13.             set { _id = value; }
  14.         }
  15.  
  16.         /// <summary>
  17.         /// get/set name of flex box item
  18.         /// </summary>
  19.         public string name
  20.         {
  21.             get { return _name; }
  22.             set { _name = value; }
  23.         }
  24.  
  25.         /// <summary>
  26.         /// constructor with id and name as parameters
  27.         /// </summary>
  28.         /// <param name="fid"></param>
  29.         /// <param name="fname"></param>
  30.         public FlexBoxItem(string flexbox_id, string flexbox_name)
  31.         {
  32.             _id = flexbox_id;
  33.             _name = flexbox_name;
  34.         }
  35.  
  36.     }
  37.  
  38.     [Serializable()]
  39.     public class FlexBoxResult
  40.     {
  41.         List<FlexBoxItem> _results = null;
  42.  
  43.         /// <summary>
  44.         /// get/set flexbox item list
  45.         /// </summary>
  46.         public List<FlexBoxItem> results
  47.         {
  48.             get { return _results; }
  49.             set { _results = value; }
  50.         }
  51.  
  52.         /// <summary>
  53.         /// constructor with flexbox item list
  54.         /// </summary>
  55.         /// <param name="_list"></param>
  56.         public FlexBoxResult(List<FlexBoxItem> _list)
  57.         {
  58.             _results = _list;
  59.         }
  60.     }
  61.  
and In ASPX page,

Expand|Select|Wrap|Line Numbers
  1. protected void Page_Load(object sender, EventArgs e)
  2.         {
  3.             DataTable dt = new DataTable();
  4.             dt.Columns.Add("Name");
  5.             dt.Columns.Add("Value");
  6.  
  7.             DataRow dr1 = dt.NewRow();
  8.             dr1["Name"] = "111";
  9.             dr1["Value"] = "abc";
  10.             dt.Rows.Add(dr1);
  11.  
  12.             DataRow dr2 = dt.NewRow();
  13.             dr2["Name"] = "222";
  14.             dr2["Value"] = "aaa";
  15.             dt.Rows.Add(dr2);
  16.  
  17.             DataRow dr3 = dt.NewRow();
  18.             dr3["Name"] = "333";
  19.             dr3["Value"] = "axx";
  20.             dt.Rows.Add(dr3);
  21.  
  22.             DataRow dr4 = dt.NewRow();
  23.             dr4["Name"] = "444";
  24.             dr4["Value"] = "bbb";
  25.             dt.Rows.Add(dr4);
  26.  
  27.            //add flex box items
  28.  
  29.             List<FlexBoxItem> _flexList = new List<FlexBoxItem>();
  30.             foreach (DataRow dr in dt.Rows)
  31.             {
  32.                 _flexList.Add(new FlexBoxItem(dr["Name"].ToString(), dr["Value"].ToString()));
  33.             }
  34.             FlexBoxResult _flexBoxResult = new FlexBoxResult(_flexList);
  35.  
  36.             JavaScriptSerializer _jss = new JavaScriptSerializer();
  37.             StringBuilder _jsonResult = new StringBuilder();
  38.             _jss.Serialize(_flexBoxResult, _jsonResult);
  39.  
  40.             Response.ContentType = "application/json";
  41.             Response.Write(_jsonResult.ToString());
  42.  
  43.         }
  44.  
it's giving me correct result..
Expand|Select|Wrap|Line Numbers
  1. {"results":[{"id":"111","name":"abc"},{"id":"222","name":"aaa"},{"id":"333","name":"axx"},{"id":"444","name":"bbb"}]}
  2.  
but, still FlexBox is not working properly..
when I put above result into a text file "json.txt" and use this text file.. it worked!!!

Expand|Select|Wrap|Line Numbers
  1.  $('#flexbox1').flexbox('json.txt'); 
Not sure.. whats exactly going wrong.. :(
Dec 1 '09 #6
ssnaik84
149 100+
ohh... i tried to access the ASPX page directly.. its source code is..

Expand|Select|Wrap|Line Numbers
  1. {"results":[{"id":"111","name":"abc"},{"id":"222","name":"aaa"},{"id":"333","name":"axx"},{"id":"444","name":"bbb"}]}
  2.  
  3. <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
  4.  
  5. <html xmlns="http://www.w3.org/1999/xhtml" >
  6. <head><meta http-equiv="Content-Type" content="application/json" /><title>
  7.  
  8. </title></head>
  9. <body>
  10.     <form name="form1" method="post" action="flexbox-results.aspx" id="form1">
  11. <div>
  12. <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTUxOTgwMTYyM2Rk1ij6LlTB68zrJMZ/5e3O8f9N/Q4=" />
  13. </div>
  14.  
  15.     <div>
  16.     </div>
  17.     </form>
  18. </body>
  19. </html>
  20.  
How I can avoid the extra HTML content?
Dec 1 '09 #7
Frinavale
9,735 Expert Mod 8TB
Delete it from your ASPX page.
;)

-Frinny
Dec 1 '09 #8
ssnaik84
149 100+
..and thats done...!!! :)
just added Response.End();

Expand|Select|Wrap|Line Numbers
  1. Response.ContentType = "application/json";
  2. Response.Write(_jsonResult.ToString());
  3. Response.End();
  4.  
  5.  
thanks a million again Frinny.. :)

- Swapnil
Dec 1 '09 #9
Frinavale
9,735 Expert Mod 8TB
Glad you got it to work :)

-Frinny
Dec 1 '09 #10

Sign in to post your reply or Sign up for a free account.

Similar topics

0
by: Santa | last post by:
I am using Fritz Onion's "Asynchronous Pages" approach as mentioned in the article http://msdn.microsoft.com/msdnmag/issues/03/06/Threading/default.aspx to increase the performance of my ASPX...
4
by: Jim Mitchell | last post by:
I tried the following to return an XML string, but it did not seem to return XML Any ideas? Thanks in advance. Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
0
by: Santa | last post by:
I am using Fritz Onion's "Asynchronous Pages" approach as mentioned in the article http://msdn.microsoft.com/msdnmag/issues/03/06/Threading/default.aspx to increase the performance of my ASPX...
2
by: kermit | last post by:
I have a .net aspx page MyPage.aspx (client side) with code behind MyPage.aspx.vb (server side). I use the Page_Load event in MyPage.aspx.vb to load data into a multiteir class based...
2
by: anoop | last post by:
Hello, I created a Public class in .aspx.vb code behind file, now I want to know can I call that functions in the class in the Scripts either client side or server side in .aspx page. also I want...
3
by: xhe | last post by:
I found Jason is a very handy data format for client/server communication. But I just met a problem as follows: I want to read the data replied from server in Jason format, the reply is like...
2
crabpot8
by: crabpot8 | last post by:
I am working on a message system that will let out programmers easily output a message to any user. It works fine, unless the message is requested inside of a page_load on an aspx page. Then, it does...
2
pradeepjain
by: pradeepjain | last post by:
i have a page post2.php which prints the json array like { page: 1, total: 239, rows: }, {id:'238',cell:}, {id:'237',cell:}, {id:'236',cell:}, {id:'235',cell:},
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.