2016-12-01 65 views
0

我使用visual studio 2015,我的項目是ASP.NET Web應用程序。使用Web表單模板。如何從jQuery ajax調用webmethod?

我不能調用從jQuery AJAX

這裏一個WebMethod是我的網頁表單的aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="WebForm2.aspx.cs" Inherits="EquipmentSubmitter.WebForm2" %> 

<!DOCTYPE html> 

<html xmlns="http://www.w3.org/1999/xhtml"> 
<head runat="server"> 
    <title></title> 
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js" type="text/javascript"></script> 
    <script type="text/javascript"> 
     function ShowCurrentTime() { 
      $.ajax({ 
       type: "POST", 
       url: "WebForm2.aspx/GetCurrentTime", 
       data: '{name: "' + $("#<%=txtUserName.ClientID%>")[0].value + '" }', 
       contentType: "application/json; charset=utf-8", 
       dataType: "json", 
       success: OnSuccess, 
       failure: function (response) { 
        alert(response.d); 
       } 
      }); 
     } 
     function OnSuccess(response) { 
      alert(response.d); 
     } 
    </script> 
</head> 
<body> 
    <form id="form1" runat="server"> 
     <div> 
      Your Name : 
      <asp:TextBox ID="txtUserName" runat="server"></asp:TextBox> 
      <input id="btnGetTime" type="button" value="Show Current Time" 
       onclick="ShowCurrentTime()" /> 
     </div> 
    </form> 
</body> 
</html> 

這裏是我的網頁表單aspx.cs

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Web; 
using System.Web.UI; 
using System.Web.UI.WebControls; 

namespace EquipmentSubmitter 
{ 
    public partial class WebForm2 : System.Web.UI.Page 
    { 
     protected void Page_Load(object sender, EventArgs e) 
     { 

     } 

     [System.Web.Services.WebMethod] 
     public static string GetCurrentTime(string name) 
     { 
      return "Hello " + name + Environment.NewLine + "The Current Time is: " 
       + DateTime.Now.ToString(); 
     } 
    } 
} 

裏面的斷點webmethod永遠不會到達。

BundleConfig.cs或其他地方有什麼應該更改嗎?

+0

你可以嘗試 'URL: 「WebForm2/GetCurrentTime」'?你不應該需要.aspx。 – mrogers

+0

ajax調用中'data:'的定義顯示不正確。 'data:{name:$(「#txtUserName」)。val()}' – Steve

+0

不幸的是,沒有任何建議起作用 – Baso

回答

0

您的網絡方法是GET並且您正在發送data - data用於POST方法。將您的網址更改爲:

url: "WebForm2.aspx/GetCurrentTime?name=" + $("#<%=txtUserName.ClientID%>")[0].value 
+0

我試過了你的建議,但沒有任何幫助。 – Baso

0

我找到了問題的答案。

文件中

RouteConfig.cs我改變了這一行

settings.AutoRedirectMode = RedirectMode.Permenant; 

對此

settings.AutoRedirectMode = RedirectMode.Off;