<< Back to article

jQuery with ASP.NET examples : Ajax & JSON Sample


Receive JSON data from server

Retrive JSON data from server
Code:
    function getJSONResponse()
    {
        $("#serverResponse").load("JSONCall.aspx");
    }
    
    Server side code:
    protected void Page_Load(object sender, EventArgs e)
    {
        // create sample datatable
        DataTable dtJSON = new DataTable();

        // add test columns to table
        dtJSON.Columns.Add("Index");
        dtJSON.Columns.Add("ItemCode");
        dtJSON.Columns.Add("Price");

        // generate random data and add 10 records in temp table
        Random randomNo = new Random();

        for (int i = 0; i < 10; i++)
        {
            dtJSON.Rows.Add(i
                            , generateRandomString(5) + "-" + generateRandomString(5)
                            , randomNo.Next(99, 500));
        }


        // generate JSON string out of the temp datatable and write it in response of the page
        Response.Write(datatableToJSON(dtJSON));
        Response.Expires = -1;
    }

    public static string generateRandomString(int length)
    {
        string randomString = Guid.NewGuid().ToString("N");
        randomString = randomString.Substring(0, length);
        return randomString;
    }

    public static string datatableToJSON(DataTable dt)
    {
        StringBuilder jsonStringBuilder = new StringBuilder();
        StringWriter jsonStringWriter = new StringWriter(jsonStringBuilder);

        JsonWriter jsonWriter = new JsonTextWriter(jsonStringWriter);

        if (dt != null && dt.Rows.Count > 0)
        {
            jsonWriter.Formatting = Formatting.None;

            jsonWriter.WriteStartArray();
            for (int i = 0; i < dt.Rows.Count; i++)
            {
                jsonWriter.WriteStartObject();
                for (int j = 0; j < dt.Columns.Count; j++)
                {
                    jsonWriter.WritePropertyName(dt.Columns[j].ColumnName.ToString().ToLower());
                    jsonWriter.WriteValue(dt.Rows[i][j].ToString());
                }
                jsonWriter.WriteEndObject();
            }
            jsonWriter.WriteEndArray();

            return jsonStringBuilder.ToString();
        }
        else
        {
            return null;
        }
    }
        

Receive JSON data from server, parse and build grid from JSON Data

Retrive JSON data from serve, parse and build grid from JSON data
Code:
            $.ajax({type:"POST", // jQuery ajax with POST method
                url: "JSONCall.aspx", // Call page JSONCall.aspx
                success:function(serverResponseData) // On success call function
                {
                    dtItems = eval("(" + serverResponseData + ")"); // evaluate retrived data to javascript object
                    
                    var htmlGrid = "";
                    
                    htmlGrid += "<table cellspacing=\"0\" cellpadding=\"4\" border=\"0\" class=\"grid\"><tr class=\"gridHeader\"><th scope=\"col\">Index</th><th scope=\"col\">Item Code</th><th scope=\"col\">Price</th></tr>";
                    
                    for(var i=0;i<dtItems.length;i++) // traverse through items in this object
                    {
                        var rowClass = (i%2 == 0) ? "gridRow" : "gridRowAlternate";
                        htmlGrid += "<tr class=\""+rowClass+"\"><td>"+dtItems[i].index+"</td><td>"+dtItems[i].itemcode+"</td><td>"+dtItems[i].price+"</td></tr>";
                        // Build grid from retrived data in current item
                    } 
                    
                    htmlGrid += "</table>";
                    
                    $("#divJSONGrid").html(htmlGrid); // apply created grid HTML to a div "divJSONGrid"
                }
                }); 
    

For more information:


<< Back to article