Click here to Skip to main content
15,885,767 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
When I click btn1 the json1 string is correct but it does not execute the "post" because the alert does not show. If I remove json and the "(int id)" in the controller the thing functions correctly.

How do I add a json object as an input to a function in the controller?
HTML
<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 = parseInt($("#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");
                $("#id").val(data[0].Id);
                $("#col1").val(data[0].col1);
                $("#col2").val(data[0].col2);
                $("#col3").val(data[0].col3);
            },"json");
        });


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))
    {
        using (SqlCommand cmd = new SqlCommand(cmdStr, conn))
        {
            conn.Open();
            cmd.Parameters.AddWithValue("@Id", id);
            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
Comments
SrikantSahu 26-Feb-15 9:50am    
Hi,
No need to stringify the Json object.
Just send the Json object directly, i.e. pass data1 to your $.post

Thanks
Sroikant
teledexterus 26-Feb-15 10:18am    
That was it . )Thanks.

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