Click here to Skip to main content
15,877,376 members
Please Sign up or sign in to vote.
4.00/5 (4 votes)
See more:
Hello Friends,
I have converted datatable to Json and accessing it on clientside. I'm stuck of how to use this Json Object.
I want to display the result in table format
Here I paste my code:

[System.Web.Services.WebMethod()]
    public static Dictionary<string,object> getWIPComments()
    {
        DataTable objDT = new DataTable();
        objDT.TableName = "mydt";
        try
        {
            StringBuilder strQuery = new StringBuilder();
            strQuery.Append("select jobno,commenttext from tbl_workinprogress_comments where jobno in ( ");
            strQuery.Append(" select jobno from tbl_planning P ");
            strQuery.Append(" inner join tbl_mechanicalbrief on tbl_mechanicalbrief.mechanicalid= P.mechanicalid ");
            strQuery.Append(" where statusid in (10))");
            SqlConnection objCon = new SqlConnection("server=xxxx;Initial Catalog=xxxx;User ID=sa;Password=xxxx;pooling='true'; Max Pool Size=200;Connect Timeout=2000000;enlist=false;");
            SqlCommand objCmd = new SqlCommand();
            objCmd.CommandText = strQuery.ToString();
            objCmd.CommandType = CommandType.Text;
            objCmd.Connection = objCon;
            objCon.Open();
            SqlDataAdapter objDA = new SqlDataAdapter("", objCon);
            objDA.SelectCommand = objCmd;
            objDA.Fill(objDT);
        }
        catch(Exception e) { }
        return ToJson(objDT);
    }

    private static List<dictionary><string,>> RowsToDictonary(DataTable objDT)
    {
        List<dictionary><string,>> objs = new List<dictionary><string,>>();
        foreach (DataRow dr in objDT.Rows)
        {
            Dictionary<string,> drow = new Dictionary<string,>();
            for (int i = 0; i < objDT.Columns.Count; i++)
            {
                drow.Add(objDT.Columns[i].ColumnName, dr[i]);
            }
            objs.Add(drow);
        }
        return objs;
    }

    private static Dictionary<string,> ToJson(DataTable table)
    {
        Dictionary<string,> d = new Dictionary<string,>();
        d.Add(table.TableName, RowsToDictonary(table));
        return d;
    }</dictionary></dictionary></dictionary>


Any idea's, how to represent this data in table format on client side?

Thanks in advance.
Posted
Comments
dhage.prashant01 6-Jun-11 5:13am    
I tried following, but gives an error. Any idea where I'm going wrong?

<script type="text/javascript">
$(document).ready(function() {
$('#imgComment').click(function() {
$('#msg').slideToggle("fast", "");
$.ajax({
type: "Post",
url: "WIPCommentsNotification.aspx/getWIPComments",
data: "{}",
dataType: "json",
contentType: "application/json; charset=utf-8",
success: function(data) {
if (data != 'null') {
//response = eval('(' + data + ')');
//$(outputDT(data.mydt)).appendTo($('#modalbody'));
$('#body').append(outputDT(data.mydt));
}
},
error: function(event, request, settings) {
alert(msg);
}
});
})
$('#closebutton').click(function() {
$('#msg').fadeOut('slow');
})
});

function outputDT(dataTable) {
var headers = [];
var rows = [];

headers.push("<tr>");
for (var name in dataTable[0]) {
headers.push("<td>"+name+"</td>");
}
headers.push("</tr>");

for (var row in dataTable) {
rows.push("<tr>");
for (var value in dataTable[row]) {
rows.push("<td>");
rows.push(dataTable[row][value]);
rows.push("</td>");
}
rows.push("</tr>");
}
var top = "<table border='1'>";
var bottom = "</table>";
return top + headers.join("") + rows.join("") + bottom;
}
</script>

Here is final Solution:
aspx.cs file code


private static string ToString(DataTable table)
    {
        StringBuilder sb = new StringBuilder();
        StringBuilder sb1 = new StringBuilder();
        JavaScriptSerializer js = new JavaScriptSerializer();
        if (table != null)
        {
            if (table.Rows.Count > 0)
            {
                foreach (DataRow dr in table.Rows)
                {
                    sb.Append("<table><tbody><tr><td>");
                    sb.Append((dr["jobno"]));
                    sb.Append("</td><td>");
                    sb.Append((dr["commenttext"]));
                    sb.Append("</td></tr></tbody></table>");
                }
            }
        }
        //js.Serialize(sb, sb1);
        return sb.ToString();
    }



aspx file code (JQuery with AJAX Code)

$.ajax({
                            type: "Post",
                            url: "WIPCommentsNotification.aspx/getWIPComments",
                            data: "{}",
                            dataType: "json",
                            contentType: "application/json; charset=utf-8",
                            success: function(data) {
                                try {
                                    data = data.hasOwnProperty("d") ? data.d : data;
Bind(data);
}
                                catch (e) {
                                    alert("Error!!");
                                }
                            },
                            error: function(event, request, settings) {
                                alert(msg);
                            }
                        });


 
function Bind(msg) {
            //alert("Hello");
//            var response = JSON.parse(msg);
            //            alert(response);
            try {
                var table = "<table id="tblResult" border="1" style="width:100%;"><thead> <tr><th>JobNo</th>  <th>Comment</th>  </tr></thead>  <tbody>";
                table += msg;
                table += '</tbody></table>';
                $('#details').html(table);
            }
            catch (e){alert("Table Error!!");}
        }



Happy Coding!!
 
Share this answer
 
I searched through the articles in CP and thought this might give you an idea.

JSON Data Visualizer (for Google, Yahoo!, Bing, and Twitter) using jQuery, JavaScript, ASP.NET MVC 2.0[^]
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900