Click here to Skip to main content
Rate this: bad
good
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" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
<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;
                 //alert(newcell.childNodes);
                 if (newcell.childNodes[0] != undefined) {
                     switch (newcell.childNodes[0].type) {
                         case "text":
                             newcell.childNodes[0].value = "";
                             break;
                         case "checkbox":
                             newcell.childNodes[0].checked = false;
                             break;
                         case "select-one":
                             newcell.childNodes[0].selectedIndex = 0;
                             break;
                     }
                 }
             }
         }
         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) {
                         table.deleteRow(i);
                         rowCount--;
                         i--;
                     }
                 }
             }
             catch (e) {
                 alert(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) {
             alert('fail');
         }
          </script>
</head>
<body onload="getData();">
    <form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnablePartialRendering="true">
    </asp:ScriptManager>
     <div>
       <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">
           <TR>
                <TD><INPUT type="checkbox" name="chk"/></TD>
                <TD> 1 </TD>
                <TD> <INPUT type="text" /> </TD>
                <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>
                   </SELECT>
                </TD>
                <TD style="width:100"> </TD>
                  <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>
                   </SELECT>
                </TD>
           </TR>
      </TABLE>
    </div>
 
    </form>
</body>
</html>
 
C#:
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)
        {
        }
        [System.Web.Services.WebMethod]
        public static string Sources()
        {
            DataTable dt = new DataTable();
            SqlCommand sqlcomm = new SqlCommand();
            SqlConnection myconn = new SqlConnection(ConfigurationManager.ConnectionStrings["NorthwindDB"].ConnectionString);
            myconn.Open();
            sqlcomm.CommandText = "Select BusinessID, CountryID FROM BusinessCountry";
            SqlDataAdapter da = new SqlDataAdapter(sqlcomm.CommandText, myconn);
            da.Fill(dt);
            myconn.Close();
            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());
            ms.Close();
            return json;
        }
    }
}
 
Posted 17-May-11 13:18pm
Edited 17-May-11 13:54pm
v2
Comments
Tarakeshwar Reddy at 17-May-11 18:54pm
   
Fixed pre tags

1 solution

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

Solution 1

  Permalink  

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

  Print Answers RSS
0 George Jonsson 215
1 Kornfeld Eliyahu Peter 169
2 OriginalGriff 120
3 PIEBALDconsult 110
4 BillWoodruff 85
0 OriginalGriff 6,165
1 DamithSL 4,658
2 Maciej Los 4,087
3 Kornfeld Eliyahu Peter 3,649
4 Sergey Alexandrovich Kryukov 3,294


Advertise | Privacy | Mobile
Web01 | 2.8.141220.1 | Last Updated 17 May 2011
Copyright © CodeProject, 1999-2014
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