1

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.

Useme Alehosaini
  • 2,998
  • 6
  • 18
  • 26
RAK
  • 273
  • 1
  • 12

2 Answers2

0
[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.

Rishi Shah
  • 46
  • 6
  • I incorporated all your suggestions, but it still does not work. There is no error in the network tab either. – RAK Dec 22 '20 at 08:35
  • 1
    What is coming in network tab, is call being made in to server? or is the network tab empty? if call is being made, what is the uri, body, method etc. edit: also can you add a debugger in remove() function and check if function is being triggered? – Rishi Shah Dec 22 '20 at 08:36
  • Yes, Remove() method triggered. And now I can see that the response text is "Authentication Failed". – RAK Dec 22 '20 at 08:42
  • 1
    You can try this https://stackoverflow.com/a/20052866/7819056 – Rishi Shah Dec 22 '20 at 08:45
0

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" 
RAK
  • 273
  • 1
  • 12