简体   繁体   中英

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. The "Function has been called" alert does pop up. There are no errors in the Chrome console.

I am using ASP.NET Web Forms

The Contact.aspx.cs file:

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

<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

Blockquote

I found the answer

Just comment below line in RouteConfig file

//settings.AutoRedirectMode = RedirectMode.Permanent;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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