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