This article will analyze the cause of this exception and give the solution, including the exception recurrence, the reason for the exception, the solution, sample code download, and so on.
Abnormal recurrence
Let's first reproduce the exception with a simple sample program and then modify and resolve the problem based on this sample program.
First, declare a ScriptManager control on the page. Because the client DataTable definition and the Value-add package, you also need to introduce the Previewscript.js script:
<asp:ScriptManager ID="ScriptManager1" runat="server">
<Scripts>
<asp:ScriptReference Assembly="Microsoft.Web.Preview" Name="Microsoft.Web.Resources.ScriptLibrary.PreviewScript.js" />
</Scripts>
</asp:ScriptManager>
Next, declare an HTML button and an HTML <div>, which is used to raise calls to Web method and to display the returned DataTable:
<input id="btnGetDataTable" type="button" value="Get DataTable" onclick="return btnGetDataTable_onclick()" />
<div id="result">
</div>
In the code above, the click button invokes a client-side JavaScript function named Btngetdatatable_onclick (), which is as follows:
function btnGetDataTable_onclick()
{
PageMethods.GetDataTable(cb_getDataTable);
}
As you can see, pagemethods.getdatatable () is the client Agent for Web method with server-side named Getdatatable (). The server-side getdatatable () method is defined as follows, noting that the method must be static (static) and be [System.Web.Services.WebMethod] and [ Microsoft.Web.Script.Services.ScriptMethod] Two properties are decorated:
[System.Web.Services.WebMethod]
[Microsoft.Web.Script.Services.ScriptMethod]
public static DataTable GetDataTable()
{
DataTable myDataTable = new DataTable();
myDataTable.Columns.Add(new DataColumn("Id", typeof(int)));
myDataTable.Columns.Add(new DataColumn("Name", typeof(string)));
for (int i = 0; i < 10; ++i)
{
DataRow newRow = myDataTable.NewRow();
newRow["Id"] = i;
newRow["Name"] = string.Format("Name {0}", i);
myDataTable.Rows.Add(newRow);
}
return myDataTable;
}
The above code is very simple: a DataTable containing two columns (IDs and name) is created and 10 rows of data are populated for the DataTable.