Click here to Skip to main content
11,927,711 members (53,950 online)
Rate this:
Please Sign up or sign in to vote.
Hi I have been working with ASP.NET for a little bit but dont have a lot of javascript expereince, I am trying to use a webmethod to return the datatable pulled as a Json string using DataContractJsonSerializer but I cant seem to find out how to parse the return Json string in javscript to get the returned values, please see comments in javascript as well. I thought I could send the project as an zipped attachment but i dont see an attachment option here?? Can someone please show an example by code how to parse the Json string in javascript to get BusinessID/CountryID from the serialized string? You will need to add references to two assemblies (System.Runtime.Serialization and System.ServiceModel.Web) Your helps appreciated.

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="JsonExample._Default" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "">
<html xmlns="" >
<head runat="server">
    <title>Json Example Form</title>
     <script language="javascript" type="text/javascript">
         function addRow(tableID) {
             var table = document.getElementById(tableID);
             var rowCount = table.rows.length;
             var row = table.insertRow(rowCount);
             var colCount = table.rows[0].cells.length;
             for (var i = 0; i < colCount; i++) {
                 var newcell = row.insertCell(i);
                 newcell.innerHTML = table.rows[0].cells[i].innerHTML;
                 if (newcell.childNodes[0] != undefined) {
                     switch (newcell.childNodes[0].type) {
                         case "text":
                             newcell.childNodes[0].value = "";
                         case "checkbox":
                             newcell.childNodes[0].checked = false;
                         case "select-one":
                             newcell.childNodes[0].selectedIndex = 0;
         function deleteRow(tableID) {
             try {
                 var table = document.getElementById(tableID);
                 var rowCount = table.rows.length;
                 for (var i = 0; i < rowCount; i++) {
                     var row = table.rows[i];
                     var chkbox = row.cells[0].childNodes[0];
                     if (null != chkbox && true == chkbox.checked) {
             catch (e) {
         function getData() {
             //Get data from PageMethod / WebMethod in codebehind and pass it to onSuccess
             PageMethods.Sources(onSuccess, onFail);
         function onSuccess(result) {
             var myObject = eval('(' + result + ')');
             //how to parse through myObject and get BusinessID and CountryID from the Json string?
             //After parsing I need to set the no of rows in the html table to the no of results and select
             //the values in the dropdowns matching the results in Json string.
         function onFail(error) {
<body onload="getData();">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
       <INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
       <INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
       <input type="button" value="Save" />
       <TABLE id="dataTable" width="350px" border="1">
                <TD><INPUT type="checkbox" name="chk"/></TD>
                <TD> 1 </TD>
                <TD> <INPUT type="text" /> </TD>
                   <SELECT name="country">
                       <OPTION value="us">USA</OPTION>
                       <OPTION value="cn">China</OPTION>
                       <OPTION value="br">Brazil</OPTION>
                       <OPTION value="mx">Mexico</OPTION>
                       <OPTION value="cm">Cambodia</OPTION>
                <TD style="width:100"> </TD>
                   <SELECT name="Business">
                       <OPTION value="IT">Information Technology</OPTION>
                       <OPTION value="CL">Clothing Industry</OPTION>
                       <OPTION value="MFG">Manufacturing</OPTION>
                       <OPTION value="FD">Food</OPTION>
                       <OPTION value="FL">Fuel</OPTION>

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.Services;
using System.Text;
using System.Data;
using System.Data.Sql;
using System.Data.SqlClient;
using System.Configuration;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
namespace JsonExample
    public partial class _Default : System.Web.UI.Page
        SqlConnection conn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindDB"].ConnectionString);
        protected void Page_Load(object sender, EventArgs e)
        public static string Sources()
            DataTable dt = new DataTable();
            SqlCommand sqlcomm = new SqlCommand();
            SqlConnection myconn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindDB"].ConnectionString);
            sqlcomm.CommandText = "Select BusinessID, CountryID FROM BusinessCountry";
            SqlDataAdapter da = new SqlDataAdapter(sqlcomm.CommandText, myconn);
            StringBuilder objSb = new StringBuilder();
            string dataResult = JSON(dt);
            return dataResult;

        private static string JSON(DataTable dt)
            dt.TableName = "myTable";
            StringBuilder objSb = new StringBuilder();
            DataContractJsonSerializer DCJS = new DataContractJsonSerializer(dt.GetType());
            MemoryStream ms = new MemoryStream();
            DCJS.WriteObject(ms, dt);
            string json = Encoding.Default.GetString(ms.ToArray());
            return json;
Posted 17-May-11 13:18pm
Edited 17-May-11 13:54pm
Tarakeshwar Reddy 17-May-11 18:54pm
Fixed pre tags

1 solution

Rate this: bad
Please Sign up or sign in to vote.

Solution 1


This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

  Print Answers RSS
Top Experts
Last 24hrsThis month

Advertise | Privacy | Mobile
Web01 | 2.8.151126.1 | Last Updated 17 May 2011
Copyright © CodeProject, 1999-2015
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100