简体   繁体   English

ASP.NET WebForms无法使用Ajax从javascript调用webmethod

[英]ASP.NET WebForms Unable to call webmethod from javascript using ajax

I can't seem to get this simple function working. 我似乎无法使这个简单的功能正常工作。

The AJAX call returns success but the function is never being called since the Debug.WriteLine is not showing up. AJAX调用返回成功,但是由于Debug.WriteLine没有显示,所以从未调用该函数。 The "Function has been called" alert does pop up. 确实会弹出“已调用功能”警报。 There are no errors in the Chrome console. Chrome控制台中没有错误。

I am using ASP.NET Web Forms 我正在使用ASP.NET Web表单

The Contact.aspx.cs file: 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;
    }  
}

In the Contact.aspx file 在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>

I have found the solution! 我找到了解决方案!

Authentication failed in call webmethod from jquery AJAX jQuery AJAX调用Web方法中的身份验证失败

Blockquote 块引用

I found the answer 我找到了答案

Just comment below line in RouteConfig file 只需在RouteConfig文件中的行下方注释

//settings.AutoRedirectMode = RedirectMode.Permanent; //settings.AutoRedirectMode = RedirectMode.Permanent;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM