【问题标题】:.NET Web Method not being called from javascript only Page.NET Web 方法没有被仅从 javascript 页面调用
【发布时间】:2018-02-24 22:45:06
【问题描述】:

我在 .aspx 页面的 codebhind 中有一个 web 方法,但是当我尝试访问它时,它不会仅触发页面的 webmethod。返回状态为 200,页面正在被调用,但方法被忽略。我使用 name.aspx/GetData 还是 name.aspx/Anything 都没有关系,结果是 200,但方法没有被触发。我使用 jquery Ajax 和 Postman 进行了测试。获取和发布尝试。 在 web.config 或任何其他内容中是​​否有任何需要更改的内容。

$.ajax({
                        url: '/adm/clientAccess.aspx/MyMethodInexistent',
                        data: {},
                        type: 'POST',
                        contentType: 'application/x-www-form-urlencoded',
                        dataType: 'html',
                        success: function (data) {
                           //I GET HERE even if the method doesn't exist, and if it exists, it doesn't return data.
                           alert(1);
                        },
                        error: function (response) {
                            alert(response.responseText);
                        }
                    }
                    );

【问题讨论】:

  • 如果你不发布任何代码,你比我们更了解这个问题。我们怎么可能帮你?请阅读有关如何提问的指南:stackoverflow.com/help/mcve
  • 抱歉,我现在添加了。
  • 您使用的是哪个版本的 .NET?调用该方法应该是url: '/adm/clientAccess.aspx/MyMethod',。尝试在方法中添加断点,看看是否可以到达。
  • 嗨。它是 3.5。我无法调试,因为我使用的是 Visual Studio Code,我正在远程服务器上进行测试,并且页面未编译。

标签: c# jquery .net postman webmethod


【解决方案1】:

需要使用 ScriptManager 元素启用页面方法:

<asp:ScriptManager ID="scm" runat="server" EnablePageMethods="true"/>

【讨论】:

    【解决方案2】:

    你可以试试下面的代码吗,确保方法的路径在下面的url 中是正确的。如果您正在使用页面方法,还可以在脚本管理器级别启用页面方法。

       $.ajax({
        url: '/adm/clientAccess.aspx/MyMethod',
        data: {},
        type: 'POST',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        async: "true",
        success: function (data) {
           console.log(data);
           //alert(1);
        },
        error: function (response) {
            alert(response.responseText);
        }
    }
    );
    

    【讨论】:

    • 嗨。我尝试这样做,用EnablePageMethods添加scriptManager,但结果是一样的,它返回整个页面,它不会触发方法,我仍然可以调用一个存在的方法。
    • 哇,好消息,它适用于 contentType:“application/json; charset=utf-8”。这是一切的结合。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-02-24
    • 1970-01-01
    • 1970-01-01
    • 2019-10-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多