简体   繁体   中英

Return Json string from C# and display it in Textbox using javascript and jquery

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

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

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> 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM