【问题标题】:ASP.NET WebForms Unable to call webmethod from javascript using ajaxASP.NET WebForms 无法使用 ajax 从 javascript 调用 webmethod
【发布时间】:2017-08-09 18:52:57
【问题描述】:

我似乎无法让这个简单的功能发挥作用。

AJAX 调用返回成功,但由于 Debug.WriteLine 未显示,因此从未调用该函数。弹出“函数已调用”警报确实。 Chrome 控制台中没有错误。

我正在使用 ASP.NET Web 窗体

Contact.aspx.cs 文件:

public partial class Contact : Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        Debug.WriteLine("Contact Page loaded");
    }

    [System.Web.Services.WebMethod]
    public static string Test(string test)
    {
        Debug.WriteLine("Input param"+test);
        return test;
    }  
}

在 Contact.aspx 文件中

<button type="button" class="btn btn-info" onclick="ShowTest()">Test</button>

<script type = "text/javascript">
    function ShowTest() {            

        //Tried this also (prefered)
        //var res = PageMethods.Test("testMessage");

        var testMsg = 'This is the test message';

        $.ajax({
            type: "POST",
            url: "Contact.aspx/Test",
            data: JSON.stringify({
                test: testMsg
            }),
            dataType: 'json',
            contentType: "application/json; charset=utf-8",
            success: function (result) {
                alert('It worked! ' + result.d);
            },
            error: function (result) {
                alert('Nope');
            }
        });

        alert("Function has been called");
    }       
</script>

【问题讨论】:

  • 成功函数中的result是什么?出于好奇,您在哪里寻找 Debug.WriteLine 输出?
  • 嗨,大卫。结果显示未定义。
  • 输出显示在 Visual Studio 控制台中。我确实显示了“已加载联系页面”。
  • 我正在做的是从网页调用 C# 代码的标准方式吗?还有比ajax更好的方法吗?
  • 不,这应该是相当标准的。虽然我可能遗漏了一些明显的东西,但我已经很久没有做过 WebForms 了。在浏览器的调试工具中,服务器对 AJAX 调用的响应是什么?

标签: javascript asp.net ajax


【解决方案1】:

我找到了解决办法!

Authentication failed in call webmethod from jquery AJAX

块引用

我找到了答案

只需在 RouteConfig 文件中的以下行注释

//settings.AutoRedirectMode = RedirectMode.Permanent;

【讨论】:

  • 我不知道它的用途,但在这一点上,我很高兴它能正常工作。多么可怕的错误。
猜你喜欢
  • 1970-01-01
  • 2011-10-19
  • 2011-07-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-18
  • 1970-01-01
相关资源
最近更新 更多