使用 Ajax 从客户端调用服务器端代码






4.32/5 (14投票s)
Ajax PageMethods 在 JavaScript 中用于在客户端调用服务器端方法
引言
使用 Microsoft ASP.NET AJAX 可以通过客户端脚本从浏览器调用 ASP.NET Web 服务(*.asmx 文件)。该脚本可以调用包含基于服务器的方法(Web 方法)的 Web 服务,并调用这些方法,而无需回发和刷新整个页面。本文中我们将使用的选项涉及 PageMethods
。 PageMethod
基本上是一个 public static
方法,它在 aspx 页面的代码隐藏中公开,并且可以从客户端脚本调用。 PageMethods
使用 [WebMethod]
特性进行注释。 页面方法呈现为内联 JavaScript。
步骤 1
创建一个启用 ASP.NET AJAX 的网站。转到文件 > 新建 > 网站 > ASP.NET AJAX 启用网站。给解决方案一个名称和位置,然后单击确定。
第二步
拖放标签和文本框控件。我们将在文本框中接受用户的 CustomerID
,并在标签中显示 'ContactName
'。 在 web.config 文件中的 Config 部分标签中添加连接字符串。
步骤 3
目前我们将添加一个方法 ‘GetContactName()
’,它将接受一个 CustomerID
,并从 Northwind 数据库的 Customer
表中返回联系人姓名信息。 然后,我们将此方法转换为 PageMethod
。
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();
}
}
步骤 4
我们现在将此方法转换为 PageMethod
,然后从客户端代码(即使用 JavaScript)调用此方法 GetContactName()
。 要将方法作为 PageMethod
启用,请在方法顶部添加属性 [WebMethod]
。
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}
同时,将属性 EnablePageMethods="true"
添加到 ScriptManager
。
步骤 5
现在让我们创建将调用此服务器端代码的 JavaScript。添加一个名为 *script.js* 的 JavaScript 文件。
function CallMe(src,dest)
{
var ctrl = document.getElementById(src);
// call server side method
PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
}
// set the destination textbox value with the 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()
事件中添加这些代码行
if (!Page.IsPostBack)
{
txtId1.Attributes.Add("onblur",
"javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
txtId2.Attributes.Add("onblur",
"javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");
}
如上所示,我们正在使用 Attributes.Add
,它允许我们向服务器控件的 System.Web.UI.AttributeCollection
对象添加一个属性。 保存在 *script.js* 文件中的函数 ‘CallMe
’ 将被调用。 我们将源和目标文本框作为参数传递。 源文本框将包含 CustomerID
。 将在 Customers
表中查找 CustomerID
,并在目标文本框中检索相应的 'ContactName
'。
祝你好运...谢谢!
历史
- 2009年5月25日:初始发布