文章目錄
- Our "Contact Us" Form In ASP.NET
- Our Page Method Exposed to ASP.NET AJAX
原文地址:http://www.singingeels.com/Articles/Using_Page_Methods_in_ASPNET_AJAX.aspx
作者:Timothy Khouri
看標題很容易聯想到updatepanel方式的頁面方法調用,而文中所指的是在用戶端非同步呼叫webservice的方式.而且用了很簡潔的代碼來說明調用的方法.
作者用一個contact us頁來描述.
首先建立一個表單:
Our "Contact Us" Form In ASP.NET <form runat="server">
<asp:ScriptManager ID="ScriptManager" runat="server"
EnablePageMethods="true" />
<fieldset id="ContactFieldset">
<label>
Your Name
<input type="text" id="NameTextBox" /></label>
<label>
Email Address
<input type="text" id="EmailTextBox" /></label>
<label>
Your Message
<textarea id="MessageTextBox"></textarea></label>
<button onclick="SendForm();">
Send</button>
</fieldset>
</form> 然後是webservice檔案
Our Page Method Exposed to ASP.NET AJAX using System;
using System.Web.Services;
public partial class ContactUs : System.Web.UI.Page
{
[WebMethod]
public static void SendForm(string name, string email, string message)
{
if (string.IsNullOrEmpty(name))
{
throw new Exception("You must supply a name.");
}
if (string.IsNullOrEmpty(email))
{
throw new Exception("You must supply an email address.");
}
if (string.IsNullOrEmpty(message))
{
throw new Exception("Please provide a message to send.");
}
// If we get this far we know that they entered enough data, so
// here is where you would send the email or whatever you wanted
// to do
}
}
最後是表單檔案裡需要調用的javascript
function SendForm() {
var name = $get("NameTextBox").value;
var email = $get("EmailTextBox").value;
var message = $get("MessageTextBox").value;
PageMethods.SendForm(name, email, message,
OnSucceeded, OnFailed);
}
function OnSucceeded() {
// Dispaly "thank you."
$get("ContactFieldset").innerHTML = "<p>Thank you!</p>";
}
function OnFailed(error) {
// Alert user to the error.
alert(error.get_message());
}
所有的一切經過原文作者描述後會發現,原來是這麼簡單.