使用带有c#的asp.net将数据库表值转换为json [英] Convert the database table value into json using asp.net with c#

查看:92
本文介绍了使用带有c#的asp.net将数据库表值转换为json的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好,



i是json脚本的新手。

我正在尝试使用asp.net将数据库表值转换为json用c#。

在这里,我也将响应发送到asp.net客户端。

但是没有收到服务器端的任何响应。

所以,请让我知道我在哪里犯了错误。

请在下面找到我的代码,



设计页面:



 <%@     Page    语言  =  C#    AutoEventWireup   =  true    CodeFile   =  Default2.aspx.cs   继承  =  Default2   %>  

< !DOCTYPE html PUBLIC - // W3C // DTD XHTML 1.0 Transitional // EN http://www.w3.org/TR/xhtml1/DTD/xhtml1-transit ional.dtd >

< html xmlns = http://www.w3.org/1999/xhtml >
< head runat = server >
< title < span class =code-keyword>> Untitled Page < / title < span class =code-keyword>>
< script type = text / javascript >
function testJson(){
$ .ajax({
type: POST
url: Default.aspx
data: {}
contentType: application / json; charset = utf-8
dataType: json
成功: function (msg){
var data = eval + msg + );
var t = < span class =code-string> < table border = 1> < tr> +
< td> <强>名称< /强>< / TD> < TD> +
< strong>公司< / strong>< / td> < TD> +
< strong>地址< / strong>< / td> < TD> +
< strong>电话< / strong>< / td> < TD> +
< strong> Country< / strong>< / td> < / TR> ;
// jQuery.each(data,function(rec){
// t = t +< tr>< td>+ this.Name + < / td>< td>+
// this.Company + < / td>< td>+ this.Address +
// < / td>< td>+ this.Phone +
// < / td>< td>+ this.Country +
// < / td>< / tr>;
// });

t = t + < / table> ;

$( #jsonDiv)。 html(t);
},
错误:功能(msg){

}
} );
};


< / script >
< / head >
< 正文 >
< ; 表格 id < span class =code-keyword> = form1 RU nat = server >
< div >
< div id = jsonDiv >

< / div >
< / div >
< / form >
< / body >
< / html >









代码落后:



 使用系统; 
使用 System.Configuration;
使用 System.Data;
使用 System.Linq;
使用 System.Web;
使用 System.Web.Security;
使用 System.Web.UI;
使用 System.Web.UI.HtmlControls;
使用 System.Web.UI.WebControls;
使用 System.Web.UI.WebControls.WebParts;
使用 System.Xml.Linq;
使用 Newtonsoft.Json;
使用 System.Text;
使用 System.Data.SqlClient;

public partial class _Default:System.Web.UI.Page
{
protected void Page_Load( object sender,EventArgs e)
{

string result = DataTableToJsonWithStringBuilder(getData());
Response.Write(result);

}
public DataTable getData()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection( @ Data Source = abc\SQL2012; Initial Catalog = test; User ID = sa; Password = test @ 123);
con.Open();
SqlCommand cmd = new SqlCommand( select menuid,caption,ParentID,HasChild,isactive from menu,con);
SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(dt);

con.Close();

return dt;

}

public string DataTableToJsonWithStringBuilder(DataTable) table)
{
var jsonString = new StringBuilder();
if (table.Rows.Count > 0
{
jsonString.Append( [);
for int i = 0 ; i < table.Rows.Count; i ++)
{
jsonString.Append( {);
for int j = 0 ; j < table.Columns.Count; j ++)
{
if (j < table.Columns.Count - 1
{
jsonString.Append( \ + table.Columns [j] .ColumnName.ToString( )
+ \: + \
+ table.Rows [i] [j] .ToString()+ \,);
}
else if (j == table.Columns.Count - < span class =code-digit> 1 )
{
jsonString.Append( \ + table.Columns [j] .ColumnName.ToString()
+ \: + \
+ table.Rows [i] [j] .ToString()+ \) ;
}
}
if (i == table.Rows.Count - 1
{
jsonString.Append( }) ;
}
else
{
jsonString.Append( },);
}
}
jsonString.Append( ]) ;
}

return jsonString.ToString();

}
}





提前感谢。



我尝试过:



使用带有c#

解决方案

.ajax({
type: POST
url: Default.aspx
data: {}
contentType: application / json; charset = utf-8
dataType: json
成功: function (msg){
< span class =code-keyword> var data = eval + msg + );
var t = <表格边框= 1>< tr> +
< td>< strong>名称< / strong>< / td>< td> +
< ; strong>公司< / strong>< / td>< td> +
< strong>地址< / strong>< / td>< td> +
< strong>电话< / strong>< / td>< td> +
< strong> Country< / strong>< / td>< / tr>;
// jQuery.each(data,function(rec){
< span class =code-comment> // t = t +< tr>< td>+ this.Name +< / td> < td>+
// this.Company +< / td> < td>+ this.Address +
// < / td> < td>+ this.Phone +
// < / td> < td>+ this.Country +
// < / td> < / tr>;
// });

t = t + < span class =code-string>< / table> ;


#jsonDiv ).html(t);
},
错误: function (msg){

}
});
};


< / script >
< / head >
< body >
< 表格 id = form1 runat = server >
< div >
< div id = jsonDiv >

< / div >
< / div >
< / form >
< < span class =c ode-leadattribute> / body >
< / html >









代码落后:



 使用系统; 
使用 System.Configuration;
使用 System.Data;
使用 System.Linq;
使用 System.Web;
使用 System.Web.Security;
使用 System.Web.UI;
使用 System.Web.UI.HtmlControls;
使用 System.Web.UI.WebControls;
使用 System.Web.UI.WebControls.WebParts;
使用 System.Xml.Linq;
使用 Newtonsoft.Json;
使用 System.Text;
使用 System.Data.SqlClient;

public partial class _Default:System.Web.UI.Page
{
protected void Page_Load( object sender,EventArgs e)
{

string result = DataTableToJsonWithStringBuilder(getData());
Response.Write(result);

}
public DataTable getData()
{
DataTable dt = new DataTable();
SqlConnection con = new SqlConnection( @ Data Source = abc\SQL2012; Initial Catalog = test; User ID = sa; Password = test @ 123);
con.Open();
SqlCommand cmd = new SqlCommand( select menuid,caption,ParentID,HasChild,isactive from menu,con);
SqlDataAdapter da = new SqlDataAdapter(cmd);

DataSet ds = new DataSet();

da.Fill(dt);

con.Close();

return dt;

}

public string DataTableToJsonWithStringBuilder(DataTable) table)
{
var jsonString = new StringBuilder();
if (table.Rows.Count > 0
{
jsonString.Append( [);
for int i = 0 ; i < table.Rows.Count; i ++)
{
jsonString.Append( {);
for int j = 0 ; j < table.Columns.Count; j ++)
{
if (j < table.Columns.Count - 1
{
jsonString.Append( \ + table.Columns [j] .ColumnName.ToString( )
+ \: + \
+ table.Rows [i] [j] .ToString()+ \,);
}
else if (j == table.Columns.Count - < span class =code-digit> 1 )
{
jsonString.Append( \ + table.Columns [j] .ColumnName.ToString()
+ \: + \
+ table.Rows [i] [j] .ToString()+ \) ;
}
}
if (i == table.Rows.Count - 1
{
jsonString.Append( }) ;
}
else
{
jsonString.Append( },);
}
}
jsonString.Append( ]) ;
}

return jsonString.ToString();

}
}





提前感谢。



我尝试过:



使用带有c#的asp.net将数据库表值转换为json blockquote>

您将不得不在调试器中运行代码,在页面加载事件上放置一个断点并检查它是否触发,然后逐步执行代码并从那里开始。我要说的一件事是你应该使用一个处理程序(ashx文件)而不是aspx,或者在你的aspx页面上使用WebMethod。 asp.net正在为你输出你没有意识到的各种东西(使用Fiddler或浏览器的开发工具来检查响应),所以在编写结果之前你需要做一个Response.Clear然后是Response.End,但是使用处理程序你不必这样做,因为唯一返回的就是你自己输出的内容。


Hi all,

i am new in json script.
am trying to convert the database table value into json using asp.net with c#.
here, am also send the response to asp.net client side.
but am not receiving any response from server side.
So please let me know where i made a mistake.
please find my code below,

Design page:

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>

<!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>Untitled Page</title>
    <script type="text/javascript">
    function testJson() {
    $.ajax({
        type: "POST",
        url: "Default.aspx",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function(msg) {
            var data = eval("(" + msg + ")");
            var t = "<table border=1> <tr>" +
              "<td> <strong>Name</strong></td> <td> " +
              "<strong>Company</strong></td> <td> " +
              "<strong>Address</strong></td> <td> " +
              "<strong>Phone</strong></td> <td> " +
              "<strong>Country</strong></td> </tr> ";
//            jQuery.each(data, function(rec) {
//                t = t + " <tr> <td> " + this.Name + "</td> <td> " +
//                    this.Company + "</td> <td> " + this.Address +
//                     "</td> <td> " + this.Phone + 
//                     "</td> <td> " + this.Country + 
//                     "</td> </tr> ";
//            });

            t = t + " </table> ";

            $("#jsonDiv").html(t);
        },
        error: function(msg) {

        }
    });
};
    
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
    <div id="jsonDiv">
    
    </div>
    </div>
    </form>
</body>
</html>





Code behind:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.Text;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
     string result=DataTableToJsonWithStringBuilder(getData());
     Response.Write(result);

    }
    public DataTable getData()
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(@"Data Source=abc\SQL2012;Initial Catalog=test;User ID=sa;Password=test@123");
        con.Open();
        SqlCommand cmd = new SqlCommand("select menuid,caption,ParentID,HasChild,isactive from menu", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
      
        DataSet ds = new DataSet();
      
        da.Fill(dt);

        con.Close();

        return dt;
        
    }
 
    public string DataTableToJsonWithStringBuilder(DataTable table)
    {
        var jsonString = new StringBuilder();
        if (table.Rows.Count > 0)
        {
            jsonString.Append("[");
            for (int i = 0; i < table.Rows.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (j < table.Columns.Count - 1)
                    {
                        jsonString.Append("\"" + table.Columns[j].ColumnName.ToString()
                     + "\":" + "\""
                     + table.Rows[i][j].ToString() + "\",");
                    }
                    else if (j == table.Columns.Count - 1)
                    {
                        jsonString.Append("\"" + table.Columns[j].ColumnName.ToString()
                     + "\":" + "\""
                     + table.Rows[i][j].ToString() + "\"");
                    }
                }
                if (i == table.Rows.Count - 1)
                {
                    jsonString.Append("}");
                }
                else
                {
                    jsonString.Append("},");
                }
            }
            jsonString.Append("]");
        }
        
        return jsonString.ToString();
        
    }
}



thanks in advance.

What I have tried:

convert the database table value into json using asp.net with c#

解决方案

.ajax({ type: "POST", url: "Default.aspx", data: "{}", contentType: "application/json; charset=utf-8", dataType: "json", success: function(msg) { var data = eval("(" + msg + ")"); var t = "<table border=1> <tr>" + "<td> <strong>Name</strong></td> <td> " + "<strong>Company</strong></td> <td> " + "<strong>Address</strong></td> <td> " + "<strong>Phone</strong></td> <td> " + "<strong>Country</strong></td> </tr> "; // jQuery.each(data, function(rec) { // t = t + " <tr> <td> " + this.Name + "</td> <td> " + // this.Company + "</td> <td> " + this.Address + // "</td> <td> " + this.Phone + // "</td> <td> " + this.Country + // "</td> </tr> "; // }); t = t + " </table> ";


("#jsonDiv").html(t); }, error: function(msg) { } }); }; </script> </head> <body> <form id="form1" runat="server"> <div> <div id="jsonDiv"> </div> </div> </form> </body> </html>





Code behind:

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using Newtonsoft.Json;
using System.Text;
using System.Data.SqlClient;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
     
     string result=DataTableToJsonWithStringBuilder(getData());
     Response.Write(result);

    }
    public DataTable getData()
    {
        DataTable dt = new DataTable();
        SqlConnection con = new SqlConnection(@"Data Source=abc\SQL2012;Initial Catalog=test;User ID=sa;Password=test@123");
        con.Open();
        SqlCommand cmd = new SqlCommand("select menuid,caption,ParentID,HasChild,isactive from menu", con);
        SqlDataAdapter da = new SqlDataAdapter(cmd);
      
        DataSet ds = new DataSet();
      
        da.Fill(dt);

        con.Close();

        return dt;
        
    }
 
    public string DataTableToJsonWithStringBuilder(DataTable table)
    {
        var jsonString = new StringBuilder();
        if (table.Rows.Count > 0)
        {
            jsonString.Append("[");
            for (int i = 0; i < table.Rows.Count; i++)
            {
                jsonString.Append("{");
                for (int j = 0; j < table.Columns.Count; j++)
                {
                    if (j < table.Columns.Count - 1)
                    {
                        jsonString.Append("\"" + table.Columns[j].ColumnName.ToString()
                     + "\":" + "\""
                     + table.Rows[i][j].ToString() + "\",");
                    }
                    else if (j == table.Columns.Count - 1)
                    {
                        jsonString.Append("\"" + table.Columns[j].ColumnName.ToString()
                     + "\":" + "\""
                     + table.Rows[i][j].ToString() + "\"");
                    }
                }
                if (i == table.Rows.Count - 1)
                {
                    jsonString.Append("}");
                }
                else
                {
                    jsonString.Append("},");
                }
            }
            jsonString.Append("]");
        }
        
        return jsonString.ToString();
        
    }
}



thanks in advance.

What I have tried:

convert the database table value into json using asp.net with c#


You're going to have to run through your code in the debugger, put a breakpoint on the page load event and check it fires, then step through the code and go from there. One thing I'll say is that you should use a handler for this (ashx file) rather than aspx, or use a WebMethod on your aspx page. asp.net is adding all sorts of things to the output for you that you don't realise (use Fiddler or the browser's dev tools to examine the response), so you'll need to do a Response.Clear before you write the results then Response.End, but with a handler you won't have to do this as the only thing returned is what you output yourself.


这篇关于使用带有c#的asp.net将数据库表值转换为json的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆