[英语阅读笔记]Using Page Methods in 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());
}


所有的一切经过原文作者描述后会发现,原来是这么简单.
posted @ 2007-06-21 10:02  哥本哈士奇(aspnetx)  阅读(623)  评论(0编辑  收藏  举报