0

Display data values in text box. I'm generating a JSON string from datatable in C#.I need to display it in text boxes using Javascript. I've tried with following method but it's displaying empty values. seems like I missed something in my code. Here is my code

<!DOCTYPE html>

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="Scripts/jquery-1.12.1.min.js" type="text/javascript"></script>
    <script src="Scripts/jquery-2.2.1.js" type="text/javascript"></script>
    <script type="text/javascript">
        function initialize() {
            var data = JSON.parse('<%=ConvertDataTabletoString() %>');//returns "[{\"TAG1\":100,\"TAG2\":100}]"
            if (data.var1) {
                $('#TextBox1').val(data[0].TAG1);
            }
            if (data.var2) {
                $('#TextBox1').val(data[0].TAG2);
            }
        }
    </script>
</head>
<body onload="initialize()">
    <form id="form1" runat="server">
        <div>
            <asp:TextBox ID="TextBox1" runat="server"></asp:TextBox>
            <asp:TextBox ID="TextBox2" runat="server"></asp:TextBox>

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

and my code behind

public string ConvertDataTabletoString()
{
    string strcon = ConfigurationManager.ConnectionStrings["SqlCon"].ConnectionString;
    DataTable dt = new DataTable();
    using (SqlConnection con = new SqlConnection(strcon))
    {
        using (SqlCommand cmd = new SqlCommand("SELECT TOP 1 TAG1,TAG2 FROM DATATABLE1  ORDER BY 1 DESC", con))
        {
            con.Open();
            SqlDataAdapter da = new SqlDataAdapter(cmd);
            da.Fill(dt);
            System.Web.Script.Serialization.JavaScriptSerializer serializer = new System.Web.Script.Serialization.JavaScriptSerializer();
            List<Dictionary<string, object>> rows = new List<Dictionary<string, object>>();
            Dictionary<string, object> row;
            foreach (DataRow dr in dt.Rows)
            {
                row = new Dictionary<string, object>();
                foreach (DataColumn col in dt.Columns)
                {
                    row.Add(col.ColumnName, dr[col]);
                }
                rows.Add(row);
            }

            return serializer.Serialize(rows); //returns JSON string "[{\"TAG1\":100,\"TAG2\":100}]"
        }
    }
}

I tried this also.

$('#TextBox1').val(data.TAG1);

RJ10
  • 305
  • 1
  • 4
  • 18

2 Answers2

1

You need to use AJAX to query the method via Pure JS or JQuery. For this to be possible, you have to make the method a webmethod and static like this to allow accessibility.

<Webmethod>
public static string ConvertDataTabletoString()

I prefer JQuery, so read example on how to use AJAX via JQuery to query a method from a codebehind via this JQuery AJAX. Snippet is shown below

 var myurl="page.aspx/ConvertDataTabletoString"
$.ajax({
      url: myurl,
      beforeSend: function( xhr ) {
        xhr.overrideMimeType( "text/plain; charset=x-user-defined" );
      }
    })
      .done(function( data ) {//data is your json in this scenario
        //write to the textbox here

      });

I also notice you are using two different versions of JQUery, this can cause conflict. Stick to one

Ammog
  • 124
  • 3
  • Altough I agree that this particular case would be better suited in an ajax call. I disagree that it's not possible to render server-side code as json. It's a pretty common pattern for rendering configurations for client side. Take this for example: http://stackoverflow.com/questions/3365551/asp-net-mvc-how-to-convert-view-model-into-json-object – smoksnes Mar 10 '16 at 07:24
  • I know that it is possible to call a server side method from the html source into a control; but the question centered around JS. – Ammog Mar 10 '16 at 09:00
1

Your code seems to work fine, but where where is data.var1 coming from? As long as your backend code actually returns what you say the snippet below will work.

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <script type="text/javascript">
        function initialize() {
            var data = JSON.parse('[{\"TAG1\":100,\"TAG2\":200}]');
          $('#TextBox1').val(data[0].TAG1);
          $('#TextBox2').val(data[0].TAG2);
        }
    </script>
</head>
<body onload="initialize()">
    <form id="form1" runat="server">
        <div>
            <input type="textbox" ID="TextBox1" />
            <input type="textbox" ID="TextBox2" />
        </div>
    </form>
  </body>
smoksnes
  • 10,509
  • 4
  • 49
  • 74