取自http://www.dotnetcurry.com/ShowArticle.aspx?ID=109&AspxAutoDetectCookieSupport=1 更多想法Google Search
第 1 步:创建一个支持 ASP.NET AJAX 的网站。转到文件 > 新建 > 网站 > 启用 ASP.NET AJAX 的网站。为解决方案指定名称和位置,然后单击“确定”。
第 2 步:拖放 2 个标签和 4 个文本框控件。我们将在 2 个文本框中接受用户的 CustomerID,并在其他两个文本框中显示“ContactName”。将显示“ContactName”的文本框设置了一些属性,使其显示为没有边框的标签。只需设置 BorderStyle=None、BorderColor=Transparent 和 ReadOnly=True。标记将类似于以下内容:
<form id="form1" runat="server">
<asp:ScriptManager ID="ScriptManager1" runat="server"/>
<div>
<asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>
<asp:TextBox ID="txtId1" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
ReadOnly="True"></asp:TextBox><br />
<br />
<asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2"></asp:Label>
<asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br />
<asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"
ReadOnly="True"></asp:TextBox> <br />
</div>
</form>
在继续之前,我们会将连接字符串信息存储在 Web.config 中。在您的 </configSections> 标签下方添加以下标签。请记住,我们已经创建了一个“启用 ASP.NET AJAX 的网站”。标签 </configSections> 以及其他一些标签会自动添加到 web.config。
<connectionStrings>
<removename="all"/>
<addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>
</connectionStrings>
第 3 步:目前我们将添加一个方法“GetContactName()”,该方法将接受 CustomerID 并从 Northwind 数据库 Customer 表中返回联系人姓名信息。然后我们将此方法转换为 PageMethod。
C#
public static string GetContactName(string custid)
{
if (custid == null || custid.Length == 0)
return String.Empty;
SqlConnection conn = null;
try
{
string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
conn = new SqlConnection(connection);
string sql = "Select ContactName from Customers where CustomerId = @CustID";
SqlCommand cmd = new SqlCommand(sql, conn);
cmd.Parameters.AddWithValue("CustID", custid);
conn.Open();
string contNm = Convert.ToString(cmd.ExecuteScalar());
return contNm;
}
catch (SqlException ex)
{
return "error";
}
finally
{
conn.Close();
}
}
VB.NET
Public Shared Function GetContactName(ByVal custid As String) As String
If custid Is Nothing OrElse custid.Length = 0 Then
Return String.Empty
End If
Dim conn As SqlConnection = Nothing
Try
Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
conn = New SqlConnection(connection)
Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"
Dim cmd As SqlCommand = New SqlCommand(sql, conn)
cmd.Parameters.AddWithValue("CustID", custid)
conn.Open()
Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())
Return contNm
Catch ex As SqlException
Return "error"
Finally
conn.Close()
End Try
End Function
第 4 步:我们现在将此方法转换为 PageMethod,然后从客户端代码调用此方法 GetContactName();即使用 JavaScript。要将方法启用为 PageMethod,请在方法顶部添加属性 [WebMethod]:
C#
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}
VB.NET
<System.Web.Services.WebMethod()> _
Public Shared Function GetContactName(ByVal custid As String) As String
结束函数
同时在ScriptManager中添加属性EnablePageMethods="true"如下图:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
第 5 步:现在让我们创建将调用此服务器端代码的 JavaScript。将一个名为 script.js 的 javascript 文件添加到您的解决方案中(右键单击项目 > 添加新项目 > Jscript 文件 > 将文件重命名为 script.js)。将以下代码添加到 javascript 文件中。
function CallMe(src,dest)
{
var ctrl = document.getElementById(src);
// call server side method
PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
}
// 使用 ContactName 设置目标文本框值
function CallSuccess(res, destCtrl)
{
var dest = document.getElementById(destCtrl);
dest.value = res;
}
// alert message on some failure
function CallFailed(res, destCtrl)
{
alert(res.get_message());
}
第 6 步:我们现在需要从我们的 aspx 页面引用这个 JavaScript 文件,并在文本框失去焦点时调用“CallMe()”方法。这样做:
在body标签中添加对javascript文件的引用,如下所示:
<body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
<form id="form1" runat="server">
…………
第 7 步:要在文本框失去焦点时调用方法,请在 Page_Load() 事件中添加这些代码行
C#
if (!Page.IsPostBack)
{
txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");
}
VB.NET
If (Not Page.IsPostBack) Then
txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")
txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")
End If
如上所示,我们使用了 Attributes.Add,它允许我们向服务器控件的 System.Web.UI.AttributeCollection 对象添加一个属性。将调用保存在“script.js”文件中的函数“CallMe”。我们将源文本框和目标文本框作为参数传递。源文本框将包含 CustomerID。将在客户表中查找客户 ID,并在目标文本框中检索相应的“联系人姓名”。
这就是从客户端调用服务器端代码所需的全部内容。运行代码。在第一个文本框中输入“ALFKI”,然后按 Tab 键。您将看到 javascript 函数继续运行并使用 PageMethods.GetContactName 调用 PageMethod GetContactName()。它传递包含 CustomerID 的源文本框的值。返回的“ContactName”显示在第一个文本框下方的第二个文本框中,在我们的例子中显示的值为“Maria Anders”。
疑难解答:“PageMethods Is 'Undefined'”错误
-
尝试在脚本管理器标签中设置 EnablePageMethods="true"
-
不要在<head /> 部分添加javascript 引用或代码。将其添加到<body> 标记中。
页面方法需要在后面的代码中是静态的。
我希望您对如何使用 JavaScript 调用服务器端代码有所了解。我已经在一些项目中成功地使用了这种技术,并且非常喜欢和欣赏 PageMethods。我希望你觉得这篇文章有用,我感谢你查看它。本文的源代码可以从这里下载。