简体   繁体   中英

How to call a method from asp.net .cs page from javascript?

I am trying to call the method insert which is in Edit.aspx.cs but it is not calling

    <script src="jquery-2.0.2.js"></script>

   <script language="javascript">
               function insert() {

              $.ajax({
              type: "POST",
              url: "Edituser.aspx.cs/insert",
               success: function () { alert('success'); },
               error: function () { alert('error'); }

                });


              }


</script>

 <input type="button" id="Button1" style="display: none" onclick="changecourse(); insert();"  value="add" />

My codebehind

    public void insert()
    {
        string a = Hidden1.Value;
        string UserId = Convert.ToString(Session["LoginId"]);
        con.Open();
        SqlCommand cmd = new SqlCommand("INSERT INTO UserDepot (UserId,DepotId)" +
            "VALUES ('" + UserId + "','" + a + "')", con);
        cmd.ExecuteNonQuery();
        con.Close();
    }

For it to work, ensure that the method location set in url is correct and that the method is public and static and that is has a [WebMethod] attribute added such as:

[WebMethod]
public static void doAll()
{
    //do something
}

if the url is "/Default.aspx/insert" then your method should look like this:

[WebMethod]
public static void insert()
{
    //do something
}

Send a QueryString to edit user to aspx

$.ajax({
          type: "POST",
          url: "Edituser.aspx?run=add",
           success: function () { alert('success'); },
           error: function () { alert('error'); }

            });

then put a if to pageload of Edituser.aspx

if (Request.QueryString["run"] == "add")
            {
               insert();//your Function Name
            }

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