By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
435,106 Members | 2,474 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 435,106 IT Pros & Developers. It's quick & easy.

How to return JSON data from ASPX page?

ssnaik84
100+
P: 149
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

Share this Question
Share on Google+
9 Replies


Frinavale
Expert Mod 5K+
P: 9,731
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
100+
P: 149
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
100+
P: 149
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
Expert Mod 5K+
P: 9,731
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
100+
P: 149
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
100+
P: 149
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
Expert Mod 5K+
P: 9,731
Delete it from your ASPX page.
;)

-Frinny
Dec 1 '09 #8

ssnaik84
100+
P: 149
..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
Expert Mod 5K+
P: 9,731
Glad you got it to work :)

-Frinny
Dec 1 '09 #10

Post your reply

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