2013-08-17 111 views
0

我想使用Ajax調用C#函數,但調用不工作。腳本顯示hello消息,但不顯示成功/錯誤消息。我做錯了什麼Ajax調用c#函數不工作

Java腳本的

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#btnsave1').click(function() { 
      alert("hello"); 
      $.ajax({ 
       type: "POST", 
       contentType: "application/json; charset=utf-8", 
       url: "LeaveSurrender.aspx/apply", 
       dataType: "json", 
       success: function() { 
        alert('Successfully Saved'); 
        // window.location.href = "ClubCreation.aspx"; 
       }, 
       Error: function() { 
        alert('error'); 
       } 
      }); 

     }); 

    }); 

C#方法

protected void apply() 
    { 
     MessageBox.Show("hi"); 
} 

回答

2

試試這個:

[WebMethod]//write [WebMethod] 
    public static string apply()//method must be "pulic static" if it is in aspx page 
    { 
     return "Hi"; 
    } 


$.ajax({ 
       type: "POST", 
       contentType: "application/json; charset=utf-8", 
       url: "LeaveSurrender.aspx/apply", 
       dataType: "json", 
       data:'{}', 
       success: function (result) { 
        alert(result); 
        // window.location.href = "ClubCreation.aspx"; 
       }, 
       Error: function() { 
        alert('error'); 
       } 
     }); 
+0

現在的作品,謝謝:) :) :) – techno

+0

@techno? ??????? –

+0

他打電話的方式既不需要公開也不必須是webmethod。 – afzalulh

2

你需要在這裏修復幾件事。 第一張:在webforms中沒有MessageBox。變更申請()方法返回的字符串:

protected string apply() 
{ 
    return "hi!"; 
} 

二:使用'#btnsave1''#<%= btnsave1.ClientID %>'獲得服務器生成ID爲按鈕,也搭上由apply()方法返回的字符串。你的腳本應該是這樣的:

<script type="text/javascript"> 
    $(document).ready(function() { 
     $('#<%= btnsave1.ClientID %>').click(function() { 
      alert("hello"); 
      $.ajax({ 
       type: "POST", 
       contentType: "application/json; charset=utf-8", 
       url: "LeaveSurrender.aspx/apply", 
       dataType: "json", 
       success: function (data) { 
        alert(data); 
        // window.location.href = "ClubCreation.aspx"; 
       }, 
       Error: function() { 
        alert('error'); 
       } 
      }); 

     }); 

    }); 
</script> 

三:請在頁面的頭部確保您已引用的jQuery:

<head runat="server"> 
    <script src="Scripts/jquery-1.8.2.js"></script>