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>
<asp:Panel runat="server" ID="pnlFiles" />
Any help in this regard is highly appreciated.
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.