【问题标题】:How to call a webmethod from jQuery ajax?如何从 jQuery ajax 调用 webmethod?
【发布时间】:2016-12-01 17:22:25
【问题描述】:

我正在使用 Visual Studio 2015,我的项目是 ASP.NET Web 应用程序。使用 Web 表单模板。

我无法从 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>

这是我的 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 或其他任何地方有什么需要更改的吗?

【问题讨论】:

  • 你能试试 'url: "WebForm2/GetCurrentTime"' 吗?你不应该需要 .aspx。
  • 您的 ajax 调用中data: 的定义出现错误。 data: {name: $("#txtUserName").val()}
  • 很遗憾,这些建议都不起作用

标签: jquery asp.net ajax webmethod


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    我找到了问题的答案。

    在文件 RouteConfig.cs 我更改了这一行

    settings.AutoRedirectMode = RedirectMode.Permenant;
    

    到这里

    settings.AutoRedirectMode = RedirectMode.Off;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-12-07
      • 2014-08-11
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多