如何从jQuery ajax调用web方法?

时间:2016-12-01 17:22:26

标签: jquery asp.net ajax webmethod

我正在使用visual studio 2015,我的项目是ASP.NET Web Application。使用Web表单模板。

我无法从jQuery ajax中调用web方法

这是我的webform 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>

这是我的webform 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或其他任何地方是否应该更改任何内容?

2 个答案:

答案 0 :(得分:0)

您的网络方法是GET,而您发送data - data用于POST方法。将您的网址更改为:

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

答案 1 :(得分:0)

我找到了问题的答案。

文件 RouteConfig.cs 中的

我改变了这一行

settings.AutoRedirectMode = RedirectMode.Permenant;

到此

settings.AutoRedirectMode = RedirectMode.Off;