简体   繁体   中英

Asp.net url is not working url: 'insert.aspx/doSomething',

I write url in AJAX it is not working. It is not post the value in to the doSomething(string fname,int age) method I wrote the method addProject() with in method I wrote AJAX funtion send the data to insert.aspx/doSomething but it is not working.

AJAX

 function addProject() {
            $.ajax({

                type: 'POST',
                url: 'insert.aspx/doSomething',
                dataType: 'JSON',
                contentType: "application/json; charset=utf-8",
                data: { fname: $('#fname').val(), age: $('#age').val() },
                success: function (data) {
                    alert("success");

                },

                error: function (xhr, status, error) {
                    debugger;
                    console.log(xhr.responseText);
                }
            });
            }

insert.aspx

 [WebMethod]
    public static string doSomething(string fname,int age)
    {      
       SqlConnection con = new SqlConnection("server=.; Initial Catalog = jds; Integrated Security= true;");
        string sql = "insert into record values('" + fname + "','" + age + "')";
        SqlCommand cmd = new SqlCommand(sql, con);
         con.Open();
         cmd.ExecuteNonQuery();
         con.Close();
         return "Sucess";
    }

I think realized that I had this line in the ajax post wrong:

data: { fname: $('#fname').val(), age: $('#age').val() },

It should be:

data: "{fname: '" + $('#fname').val()+ "',age: '" + $('#age').val() + "'}",

As well as the WebMethod to:

public static string AddTo_Cart(string fname, int age)

i wish this resolved your problem.

You need to wrap those two property in a class then it will work. Here UserClass is custom class which contains fname and age property

public class UserClass
{
    public string fname { get; set; }
    public int age { get; set; }
}

[WebMethod]
public static string doSomething(UserClass obj)
{      
   SqlConnection con = new SqlConnection("server=.; Initial Catalog = jds; Integrated Security= true;");
    string sql = "insert into record values('" + obj.fname + "','" + obj.age + "')";
    SqlCommand cmd = new SqlCommand(sql, con);
     con.Open();
     cmd.ExecuteNonQuery();
     con.Close();
     return "Sucess";
}

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