I have a WebForms project and I have 1 page with a Datatable inside.
The relevant things are organized in this way:
Site.master:
<body>
<form runat="server">
<asp:ScriptManager runat="server" EnablePageMethods="true" ID="ScriptManager1">
<Scripts>
<asp:ScriptReference Path="~/Scripts/custom-datatable.js" />
The WebMethod in Default.aspx.cs:
[System.Web.Services.WebMethod]
public static object GetAllCONTEGGI(Nullable<DateTime> dateFrom, Nullable<DateTime> dateTo, Nullable<int> idUtente, Nullable<int> eventType, Nullable<int> logType)
{
...
var result = LogReader.SearchLogEvento(dateFrom, dateTo, idUtente, string_eventType, string_logType);
return result;
}
The javascript custom-datatable.js:
$(document).ready(function () {
...
PageMethods.GetAllCONTEGGI(null, null, null, null, null, SuccessOnLoadingLoadUtentiFunzioni, OnError);
function SuccessOnLoadingLoadUtentiFunzioni(dataset){...}
function OnError(data) { }
}
The Default.aspx page:
<%@ Page Title="Home Page" Language="C#" MasterPageFile="~/Site.Master" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
...
<table id="tblConteggi" class="display">
...
<button id="btnClick" <%-- onclick="LoadDataTable();"--%> >Cerca log</button>
...
This way works fine, i.e. calling all the javascript code inside $(document).ready(function () { ...
I noted that, when clicking the button id="btnClick", the page does a postback, as I see when i set a breakpoint in
protected void Page_Load(object sender, EventArgs e)
{ ...
of Default.aspx.cs
Anyways, the PageMethod call is passed to SuccessOnLoadingLoadUtentiFunzioni when I create/load the Datatable.
What is strange for me, is that, when I add the onclick event handler in the button <button id="btnClick" onclick="LoadDataTable();" >Cerca log</button>
,
and insert all the javascript code inside that event, and not in document.ready:
LoadDataTable()
{
...
PageMethods.GetAllCONTEGGI(null, null, null, null, null, SuccessOnLoadingLoadUtentiFunzioni, OnError);
function SuccessOnLoadingLoadUtentiFunzioni(dataset){...}
function OnError(data) { }
}
, the WebMethod is called (as I see in debug), but then it doesn't pass neither through OnSuccess (SuccessOnLoadingLoadUtentiFunzioni), nor through OnError.
My questions are: 1. Aren't WebMethods supposed not to make postbacks ? 2. What causes the WebMethod not to return the response in the second case (the case when I insert the javascript code in a function and not directly in document.ready)
Thanks
Riplace with this:
<button id="btnClick" type="button" onclick="LoadDataTable();" >Cerca log</button>
You are missing type="button", this will prevent the page to postback, and will allow the response to pass to OnSuccess