Return json format data from code behind of asp.net csharp

Review following code snippet to retrive json data in c#.

String strResult = “”;
strResult += “{‘xproducts’: “;
strResult += “[“;
if (dtable.Rows.Count > 0)
{
for (int i = 0; i < dtable.Rows.Count; i++)
{
strResult += “{ “;
strResult += “‘xid’:'” + dtable.Rows[i][“Id”].ToString() + “‘, “;
strResult += “‘xname’:'” + dtable.Rows[i][“Name”].ToString() + “‘, “;
strResult += “‘xprice’:'” + dtable.Rows[i][“Price”].ToString() + “‘, “;
strResult += “} “;
if (i != dtable.Rows.Count – 1)
{ strResult += “,”; }
}

}
strResult += “]”;
strResult += “}”;

context.Response.ContentType = “text/html”;
context.Response.Write(strResult);

 

Other Post for javascript:

https://siddharthboraniait.wordpress.com/2013/09/11/show-current-date-using-javascript-in-web-browserclient-side-date-in-web-browser/

Advertisements

json parsing in javascript with jquery

Following is simple example, that uses jquery.ajax function to request json data from any url.

and once data is received,
$.each
is use for looping through all logical record in json data.

jQuery.ajax(
            {
                type: 'POST',
                url: 'http://demourl?tmp=' + Math.random(),
                dataType: 'json',
                data: 'keyword=demo&query=demoquery',
                success: function(jd) {

                    var strResult = '';

                    $.each(jd.posts, function(i, obj) {

                    var strLoop ="";

                    strLoop = strLoop +"<div class='resultrecord'>";
                    strLoop = strLoop + obj.firstname + ' ' + obj.lastname;
                    strLoop = strLoop +"</div>";

                    strResult = strResult + strLoop;
                    });

                    jQuery("#d1").html(strResult);
                }
            }
        );