2

I've retrieved data from database, and I've stored it in a 2D array (jagged).

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();

Now I've serialized this so as to pass as JSON, to be used at the client (browser). When I say Response.Write(json); it gives the following output:

 [["1","John","xyz","12000"],["2","Mike","pqr","15000"],["3","Nick","fjdu","18000"],["4","Brad","wee","22000"]]

But I want this data to be stored in JavaScript variable (say \var x) and use it as x[0][1].

Is that even possible?

3 Answers 3

4

You can create a c# function and called it from client side. the same code you will have to write in GetData function and that will return string as you have serialize using JavaScriptSerializer.

var Json = <%= GetData(); %>

That will render page like this,

var Json = [["1","John","xyz","12000"],["2","Mike","pqr","15000"],["3","Nick","fjdu","18000"],["4","Brad","wee","22000"]]

And you can access values like Json[0][0] would return 1.

Code behind

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
    }
}

Clint side (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>
Sign up to request clarification or add additional context in comments.

7 Comments

1) Are you using mvc or webform application ? 2) Make sure function returns correct json as string format. 3) is it rendering correct as expected?
i'm using asp.net web site. As said if i say Response.Write(json); then it gives proper output on browser, i.e. [["1","John","xyz","12000"],["2","Mike","pqr","15000"],["3","Nick","fjdu","18000"],["4","Brad","wee","22000"]]
var Json = <%= GetData(); %> not a good code. What if GetData() returns null! the page will be doomed.
@Rashmin Javiya : Thanx for posting the code. I tried the following on client: <script type="text/javascript" > alert('0'); var Json = <% GetData(); %> alert('1'); alert(Json[0][1]); alert('2'); </script> but when run, i'm only getting alert for 0 and 1... Neither getting alert for Json[0][1] nor for alert 2
Remove ;(semicolon) from - <%= GetData(); %>
|
0

try this

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());

then in your dom you will have the global variable name jsonObj.

Comments

0

Depending you are using MVC razor or ASP, the syntax will change a bit on view. Using MVC razor you simply has to put the string into model variable (into controller) and access into the page.

var json = @model.MyString;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.