[英語閱讀筆記]Using Page Methods in ASP.NET AJAX

來源:互聯網
上載者:User
文章目錄
  • 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());
}

所有的一切經過原文作者描述後會發現,原來是這麼簡單.

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.