Calling a WebMethod from the click event of dynamically added Button control in Asp.net does not work

547 Views Asked by At

I am unable to call the web method from the click event of the dynamically added Button control. Here is the C# Code

public partial class Default : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
         
            Button button = new Button();
            button.Text = "Click Me.";
            button.OnClientClick = "return Remove()";
            pnlFiles.Controls.Add(button);
  
       
    }

    [WebMethod]
    public void ClickEvent(int id)
    {
        
        

    }
}

Here is the javascript

<script type="text/javascript">
        function Remove() {
             
            $.ajax({
                url:"Default.aspx/ClickEvent",
                data: "{'id':5}",
                type: "POST",
                cache: false,
                headers: { "cache-control": "no-cache" },
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (msg) {

                    alert(msg);

                },
                error: function (xhr, status, error) {
         
                }
            });
         
        }
    </script>
Here is the HTML

  <asp:Panel runat="server" ID="pnlFiles" />

Any help in this regard is highly appreciated.

2

There are 2 best solutions below

4
Rishi Shah On
[WebMethod]
public void static ClickEvent(int i)
{
    
   
}

I think WebMethod should be static. Also Use JSON.stringify for data. This should solve the problem. If not, you can try and see if there is any error in network tab of chrome dev console.

Note: keep the param name of c# method same as the param you are passing in json body.

0
RAK On

jQuery $.ajax error response text was "Authentication Failed". I commented out the following line in RouteConfig.cs and it worked.

  jQuery $.ajax error response text is "Authentication Failed"