Click here to Skip to main content
15,892,746 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I can not get the json1 to read { "id":1 } for an Integer instead it reads { "id":"1" } and can not be read as an integer in the [HttpPost].

How do I get a Json Object to be read as an integer?

JavaScript
script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script type="text/javascript">
    $(function () {
        $("#btn1").click(function () {
            var id1 = $("#text1").val();
            var url1 = "/Home/function1";
            var data1 = { "id":id1 };
            var json1 = JSON.stringify(data1);
            $("#jsondata").val(json1);
            $.post(url1, json1, function (data) {
                alert("success");
            },"json");
                $("#id").val(data[0].Id);
                $("#col1").val(data[0].col1);
                $("#col2").val(data[0].col2);
                $("#col3").val(data[0].col3);
        });
</script>


C#
[HttpPost]
        public JsonResult function1(int id)
        {
            List<Table1> the1 = new List<Table1>();
            string connStr = ConfigurationManager.ConnectionStrings["conndb"].ConnectionString;
            string cmdStr = "SELECT * FROM [Table1] WHERE [Id]=@Id;";
            SqlDataReader dr = null;
            using (SqlConnection conn = new SqlConnection(connStr))
            {
                conn.Open();
                using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
                {
                    cmd.Parameters.AddWithValue("@Id", id);
                    cmd.ExecuteNonQuery();
                    using (dr = cmd.ExecuteReader())
                    {
                        while (dr.Read())
                        {
                            the1.Add(new Table1 { Id = Convert.ToInt32(dr["Id"]), col1 = dr["col1"].ToString(), col2 = dr["col2"].ToString(), col3 = dr["col3"].ToString() });
                        }
                    }
                }
            }
            return Json(the1, JsonRequestBehavior.AllowGet);
        }
Posted

1 solution

JavaScript
JSON.stringify(data1);
the above stringify() may returns the result in String values, you can use your URL as follows
"/Home/function1?id=1"
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900