我从数据库中检索了数据,并将其存储在2D数组中(锯齿状)。
SqlConnection con = new SqlConnection("Data Source=COMP7;Initial Catalog=GK_Practice;User ID=sa;Password=SQLEXPRESS");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from employee";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
int rowcount=0, columncount;
while(rd.Read())
{
rowcount++;
}
columncount = rd.FieldCount;
rd.Close();
rd = cmd.ExecuteReader();
string[][] str=new string[rowcount][];
int i = 0;
while(rd.Read())
{
str[i] = new string[columncount];
for (int j = 0; j < columncount; j++)
{
str[i][j] = rd.GetValue(j).ToString();
}
i++;
}
Label2.Text = str[1][1].ToString();
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize((object)str);
Response.Write(json);
rd.Close();
con.Close();
现在我已将其序列化以便作为JSON传递,以便在客户端(浏览器)中使用。当我说Response.Write(json);
时,它会给出以下输出:
[["1","John","xyz","12000"],["2","Mike","pqr","15000"],["3","Nick","fjdu","18000"],["4","Brad","wee","22000"]]
但我希望这些数据存储在JavaScript变量中(比如\ var x)并将其用作x [0] [1]。
这甚至可能吗?
答案 0 :(得分:4)
您可以创建一个c#函数并从客户端调用它。您必须在GetData函数中编写相同的代码,并且在使用JavaScriptSerializer
进行序列化时将返回字符串。
var Json = <%= GetData(); %>
这将呈现这样的页面,
var Json = [["1","John","xyz","12000"],["2","Mike","pqr","15000"],["3","Nick","fjdu","18000"],["4","Brad","wee","22000"]]
您可以访问Json[0][0]
之类的值将返回1。
代码
public partial class Somepage : System.Web.UI.Page
{
public string GetData()
{
SqlConnection con = new SqlConnection("Data Source=COMP7;Initial Catalog=GK_Practice;User ID=sa;Password=SQLEXPRESS");
SqlCommand cmd = new SqlCommand();
cmd.Connection = con;
cmd.CommandType = CommandType.Text;
cmd.CommandText = "select * from employee";
con.Open();
SqlDataReader rd = cmd.ExecuteReader();
int rowcount=0, columncount;
while(rd.Read())
{
rowcount++;
}
columncount = rd.FieldCount;
rd.Close();
rd = cmd.ExecuteReader();
string[][] str=new string[rowcount][];
int i = 0;
while(rd.Read())
{
str[i] = new string[columncount];
for (int j = 0; j < columncount; j++)
{
str[i][j] = rd.GetValue(j).ToString();
}
i++;
}
Label2.Text = str[1][1].ToString();
JavaScriptSerializer js = new JavaScriptSerializer();
string json = js.Serialize((object)str);
rd.Close();
con.Close();
return json;
}
protected void Page_Load(object sender, EventArgs e)
{
// Just to feel you this is code behind
}
}
克林特方面(Javascript)
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
<title></title>
<script type="text/javascript">
var Json = <%= GetData(); %>
</script>
</head>
答案 1 :(得分:0)
试试这个
var sb = new StringBuilder();
sb.Append("<script>");
sb.Append(string.Format("var jsonObj ={0}", json));
sb.Append("</script>");
ClientScript.RegisterStartupScript(this.GetType(), "jsonObjVar", sb.ToString());
然后在你的dom中你将拥有全局变量名jsonObj。
答案 2 :(得分:0)
根据您使用的是MVC razor或ASP,语法会在视图上发生一些变化。 使用MVC剃刀你只需将字符串放入模型变量(进入控制器)并访问页面。
var json = @model.MyString;