How to return JSON data from ASPX page?

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • ssnaik84
    New Member
    • Aug 2009
    • 149

    #1

    How to return JSON data from ASPX page?

    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,
    Code:
     $('#flexbox1').flexbox('flexbox-results.aspx');
    here, page "flexbox-results.aspx" needs to return JSON result.
    when I use
    Code:
    Response.ContentType = "application/json";
    Response.Write(jsonResult);
    it does not work..

    Let me know how to proceed..
    Thanks in Adv.
    Swapnil
  • Frinavale
    Recognized Expert Expert
    • Oct 2006
    • 9749

    #2
    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 JavaScriptSeria lizer class.

    -Frinny

    Comment

    • ssnaik84
      New Member
      • Aug 2009
      • 149

      #3
      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?

      Comment

      • ssnaik84
        New Member
        • Aug 2009
        • 149

        #4
        ok.. this is the code sample, I have tried..

        Code:
        protected void Page_Load(object sender, EventArgs e)
                {
                    DataTable dt = new DataTable();
                    dt.Columns.Add("Name");
                    dt.Columns.Add("Value");
        
                    DataRow dr1 = dt.NewRow();
                    dr1["Name"] = "111";
                    dr1["Value"] = "abc";
                    dt.Rows.Add(dr1);
        
                    DataRow dr2 = dt.NewRow();
                    dr2["Name"] = "222";
                    dr2["Value"] = "aaa";
                    dt.Rows.Add(dr2);
        
                    DataRow dr3 = dt.NewRow();
                    dr3["Name"] = "333";
                    dr3["Value"] = "axx";
                    dt.Rows.Add(dr3);
        
                    DataRow dr4 = dt.NewRow();
                    dr4["Name"] = "444";
                    dr4["Value"] = "bbb";
                    dt.Rows.Add(dr4);
        
        
                    //start json result
                    string jsonResult = "{'results':[";
                    jsonResult += "";
        
                    int i = 0;
                    foreach (DataRow dr in dt.Rows)
                    {
                        i++;
                        jsonResult += "{'id':'" + dr["Name"].ToString() + "',";
                        if (i < dt.Rows.Count)
                        {
                            jsonResult += "'name':'" + dr["Value"].ToString() + "'},";
                        }
                        else
                        {
                            jsonResult += "'name':'" + dr["Value"].ToString() + "'}";
                        }
        
                    }
        
                    //end json string
                    jsonResult += "]}";
        
                    //Response.Headers.Add("Content-type", "text/json");
                    //Response.Headers.Add("Content-type", "application/json");
                    Response.ContentType = "application/json";
                    Response.Write(jsonResult);
        
                }
        when I debugged, it's giving me JSON result string like..

        Code:
        {'results':[
        {'id':'111','name':'abc'},
        {'id':'222','name':'aaa'},
        {'id':'333','name':'axx'},
        {'id':'444','name':'bbb'}]}

        Comment

        • Frinavale
          Recognized Expert Expert
          • Oct 2006
          • 9749

          #5
          That article looks over complicated.

          I don't know if web services or a server control is best for your situation...I'v e 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 JavaScriptSeria lizer 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:
          Code:
          <Serializable()> Private class FlexBoxItem
            Private _name As String
            Private _id As Integer
            
            Public Property id As Integer
              Get
                return _id
              End Get
              Set (ByVal value As Integer)
                _id = value
              End Set
            End Property
          
            Public Property name As String
              Get
                return _name
              End Get
              Set (ByVal value As String)
                _name= value
              End Set
            End Property
          End Class
          Public Sub New(ByVal itemID As Integer, ByVal itemName As String)
           Me._id = itemID
           Me._name = itemName
          End Sub
          Now you need a collection of these List Items...and you have to serialize them into an Array of JSON "FlexBoxIte ms":
          Code:
          'Populating list:
          myListOfFlexBoxItems.Add(New FlexBoxItem(1,"first item"))
          myListOfFlexBoxItems.Add(New FlexBoxItem(2,"second item"))
          myListOfFlexBoxItems.Add(New FlexBoxItem(3,"third item"))
          
          'Serializing list:
          Dim jss As New JavaScriptSerializer()
          Dim jsonFlexBoxItems As New StringBuilder
          jss.Serialize(myListOfFlexBoxItems, jsonFlexBoxItems)
          
          'Now send the jsonFlexBoxItems to the browser
          Response.ContentType = "application/json";
          Response.Write(jsonFlexBoxItems.ToString);
          Please note that I have not tested this code...it's just meant to give you an idea how to use the JavaScriptSeria lizer to send the array of JSON objects to the browser.

          -Frinny

          Comment

          • ssnaik84
            New Member
            • Aug 2009
            • 149

            #6
            Thanks a lot for neat guidance.. I have tried in following way..

            Code:
            [Serializable()]
                public class FlexBoxItem
                {
                    string _id = string.Empty;
                    string _name = string.Empty;
            
                    /// <summary>
                    /// get/set id of flex box item
                    /// </summary>
                    public string id
                    {
                        get { return _id; }
                        set { _id = value; }
                    }
            
                    /// <summary>
                    /// get/set name of flex box item
                    /// </summary>
                    public string name
                    {
                        get { return _name; }
                        set { _name = value; }
                    }
            
                    /// <summary>
                    /// constructor with id and name as parameters
                    /// </summary>
                    /// <param name="fid"></param>
                    /// <param name="fname"></param>
                    public FlexBoxItem(string flexbox_id, string flexbox_name)
                    {
                        _id = flexbox_id;
                        _name = flexbox_name;
                    }
                    
                }
            
                [Serializable()]
                public class FlexBoxResult
                {
                    List<FlexBoxItem> _results = null;
            
                    /// <summary>
                    /// get/set flexbox item list
                    /// </summary>
                    public List<FlexBoxItem> results
                    {
                        get { return _results; }
                        set { _results = value; }
                    }
            
                    /// <summary>
                    /// constructor with flexbox item list
                    /// </summary>
                    /// <param name="_list"></param>
                    public FlexBoxResult(List<FlexBoxItem> _list)
                    {
                        _results = _list;
                    }
                }
            and In ASPX page,

            Code:
            protected void Page_Load(object sender, EventArgs e)
                    {
                        DataTable dt = new DataTable();
                        dt.Columns.Add("Name");
                        dt.Columns.Add("Value");
            
                        DataRow dr1 = dt.NewRow();
                        dr1["Name"] = "111";
                        dr1["Value"] = "abc";
                        dt.Rows.Add(dr1);
            
                        DataRow dr2 = dt.NewRow();
                        dr2["Name"] = "222";
                        dr2["Value"] = "aaa";
                        dt.Rows.Add(dr2);
            
                        DataRow dr3 = dt.NewRow();
                        dr3["Name"] = "333";
                        dr3["Value"] = "axx";
                        dt.Rows.Add(dr3);
            
                        DataRow dr4 = dt.NewRow();
                        dr4["Name"] = "444";
                        dr4["Value"] = "bbb";
                        dt.Rows.Add(dr4);
            
                       //add flex box items
            
                        List<FlexBoxItem> _flexList = new List<FlexBoxItem>();
                        foreach (DataRow dr in dt.Rows)
                        {
                            _flexList.Add(new FlexBoxItem(dr["Name"].ToString(), dr["Value"].ToString()));
                        }
                        FlexBoxResult _flexBoxResult = new FlexBoxResult(_flexList);
            
                        JavaScriptSerializer _jss = new JavaScriptSerializer();
                        StringBuilder _jsonResult = new StringBuilder();
                        _jss.Serialize(_flexBoxResult, _jsonResult);
            
                        Response.ContentType = "application/json";
                        Response.Write(_jsonResult.ToString());
                   
                    }
            it's giving me correct result..
            Code:
            {"results":[{"id":"111","name":"abc"},{"id":"222","name":"aaa"},{"id":"333","name":"axx"},{"id":"444","name":"bbb"}]}
            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!!!

            Code:
             $('#flexbox1').flexbox('json.txt');
            Not sure.. whats exactly going wrong.. :(

            Comment

            • ssnaik84
              New Member
              • Aug 2009
              • 149

              #7
              ohh... i tried to access the ASPX page directly.. its source code is..

              Code:
              {"results":[{"id":"111","name":"abc"},{"id":"222","name":"aaa"},{"id":"333","name":"axx"},{"id":"444","name":"bbb"}]}
              
              <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
              
              <html xmlns="http://www.w3.org/1999/xhtml" >
              <head><meta http-equiv="Content-Type" content="application/json" /><title>
              
              </title></head>
              <body>
                  <form name="form1" method="post" action="flexbox-results.aspx" id="form1">
              <div>
              <input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE" value="/wEPDwUKMTUxOTgwMTYyM2Rk1ij6LlTB68zrJMZ/5e3O8f9N/Q4=" />
              </div>
              
                  <div>
                  </div>
                  </form>
              </body>
              </html>
              How I can avoid the extra HTML content?

              Comment

              • Frinavale
                Recognized Expert Expert
                • Oct 2006
                • 9749

                #8
                Delete it from your ASPX page.
                ;)

                -Frinny

                Comment

                • ssnaik84
                  New Member
                  • Aug 2009
                  • 149

                  #9
                  ..and thats done...!!! :)
                  just added Response.End();

                  Code:
                  Response.ContentType = "application/json";
                  Response.Write(_jsonResult.ToString());
                  [B]Response.End();[/B]
                  thanks a million again Frinny.. :)

                  - Swapnil

                  Comment

                  • Frinavale
                    Recognized Expert Expert
                    • Oct 2006
                    • 9749

                    #10
                    Glad you got it to work :)

                    -Frinny

                    Comment

                    Working...