使用JQuery從用戶端調用C#方法

來源:互聯網
上載者:User

     這篇文章將協助你怎樣實現用戶端調用後台定義的方法。JQuery讓生活變的更簡單,對於它來說,這有一個很簡單的方法去實現這個目的。

(註:本文的目的是想說明怎樣使用JQuery去請求後台某個定義的方法,而非直接使用後台函數。請求背景方法有很多種,這僅僅是用戶端與服務端互動的方法之一,當然還有當下流行的WebService。看到評論中有朋友對本文的標題有深入的討論,所以在此做下說明!)

早前,我們知道一種方法:如果我們想從用戶端去調用一個後台添加的函數就需要寫一種叫的WebMethod的東西,而現在,通過下面的方法,我們將無需再用到WebMethod。

     通過下面的例子,我將寫一個方法,它的目的是當點擊刪除鍵時將會刪除一個指定的使用者。我不想回傳(postback,Web 頁將資料發送回伺服器上的同一頁的進程。),所以想從用戶端執行該事件。我在伺服器端的cs檔案中寫了一個方法,並在用戶端通過JQuery去調用它。這個頁面叫Test.aspx。而這個方法叫DeleteRec()。

1 private void DeleteRec()2 {3   int ID = Request.Form["ID"].ToString().ToInteger();4   //parameter send from client side   5   int UserID = Request.Form["UserID "].ToString().ToInteger();6   //parameter send from client side   7   UserBO lObjUserBO = new UserBO();8   lObjUserBO .DeleteUser(ID, UserID);9 }

下面將介紹如果調用這個方法: 

 

 1 protected void Page_Load(object sender, EventArgs e) 2 { 3   if (!Page.IsPostBack) 4   { 5     #region Ajax methods    6     if (Request.Form["MethodName"] == "DeleteR") 7     // same Method Name that we are specifying on client side(DeleteR)    8     { 9       DeleteRec(); // Method defined on the page to delete the record   10       return ;11     }12     #endregion 13   }14 }

 

這就是我們需要在用戶端(Test.aspx)中需要添加的。

1 <a id="adelete" href="java<!-- no -->script:void(0);">Delete</a>  

使用下需要指令碼將會在我們點擊錨標記的時候調用服務端的方法。

 1 $('#adelete').click(function()     2  {           3      var dataToSend={ID:ID,MethodName:'DeleteR',UserID :UserID };                      4      var options =           5      {           6          url: '<%=ResolveUrl("~/Test.aspx") %>?x=' + new Date().getTime(),           7          data: dataToSend,           8          dataType: 'JSON',           9          type: 'POST',          10          success: function (response) {          11          window.location.href='<%=ResolveUrl("~/Test1.aspx")%>/'+ID;          12          //after success will redirect to new page          13      }          14  }          15  $.ajax(options);  

希望上面這些能對你從用戶端調用服務端代碼有所協助。

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.