0

I'm trying to call a simple static WebMethod in my ASP.NET Webforms page using jQuery Ajax, but it doesn't seem to be working. I've tried enabling anonymous authentication and other fixes suggested online, but nothing helps.

Here's my code:

<script>
    $(document).ready(function () {
        $("#btnCall").click(function () {
            var name = $("#txtName").val();
            $.ajax({
                type: "POST",
                url: "AjaxTest.aspx/SayHello",
                data: JSON.stringify({ name: name }),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    $("#result").text(response.d);
                },
                error: function (xhr, status, error) {
                    console.error(error);
                    $("#result").text("Error: " + error);
                }
            });
        });
    });
</script>

Code-behind (AjaxTest.aspx.cs):

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string SayHello(string name)
{
    return "Hello " + name;
}

I just want to click a button, send a value to the backend, and show the returned text (Hello [name]) on the page. However, the Ajax call fails and the browser console shows an error (or nothing happens).

What I've tried:

  • Enabled anonymous authentication in IIS
  • Added [System.Web.Services.WebMethod] explicitly
  • Made sure the method is public static
  • Verified the URL and case sensitivity
  • Checked network tab (sometimes shows 500 "Internal Server Error")
1
  • It would be better to add the error messages of the network tab. Commented Nov 13 at 5:10

2 Answers 2

0

Ok, several things to check.

First up, not really sure why one is writing jQuery selector code to add an event to a button. Why not just add the event call to the button? That way, when looking at markup, you don’t have two (multiple) places to look at to determine what a button does?

And your thus writing code (that you have to check and verify) to add the event, and then you have code for the event (that you have to check and verify). Now, if you wanting to select a bunch of buttons in say a table, then by all means use a jQuery selector to add an event to all of the buttons with one bit of jQuery selector code. So, writing more code to add an event is just another place for things to fail.

Ok, so a few things to check:

Make sure the button is not causing a post-back. Just another REALLY great reason to not write code to hook up a click event, since then you have to go back and check what the button does - two places in the markup to check and look at. So, just put the code call in the button markup.

So, say this markup:

        <div style="padding:35px">
            
            <h4>Enter your name</h4>
            <asp:TextBox ID="txtName" runat="server" ClientIDMode="Static">
            </asp:TextBox>

            <br />
            <br />

            <asp:Button ID="cmdTest" runat="server" Text="ajax call test"
                cssclass="btn"
                OnClientClick="HelloTest();return false"                
                />


            <h4>Result</h4>
            <asp:TextBox ID="txtFull" runat="server" ClientIDMode="Static">
            </asp:TextBox>

        </div>

        <script>


            function HelloTest() {

                var name = $("#txtName").val()

                var sMsg = "about to call web method" +
                    "\njQuery ver = " + jQuery.fn.jquery +
                    "\nName to pass = " + name

                alert(sMsg)

                var sURL = "WebCallTestPage.aspx/SayHello"
                $.ajax({
                    type: "POST",
                    url: sURL,
                    contentType: "application/json; charset=utf-8",
                    data: JSON.stringify({ name: name }),
                    dataType: "json",
                    success: function (Data) {
                        $('#txtFull').val(Data.d)
                    },
                    error: function (xhr, status, error) {
                        var errorMessage = xhr.status + ': ' + xhr.statusText
                        alert('Error - ' + errorMessage)
                    }
                });
            }

        </script>

Note the use of ClientIDMode for the controls. If you don't do this, then you need to use "in line" server side expressions for the jQuery() selectors. And even if using an HTML button? Do include the return = false to prevent a post-back.

So, the above should produce this:

enter image description here

Ok, if above does not work, then if you are using friendly URL's, then check Global.asax, and in App_Start, comment out the following:

var settings = new FriendlyUrlSettings();
// settings.AutoRedirectMode = RedirectMode.Permanent; // <-- comment this out
routes.EnableFriendlyUrls(settings);
Sign up to request clarification or add additional context in comments.

Comments

0

Simply remove EnableSession = true since you're not actually using session data:

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static string SayHello(string name)
{
    return "Hello " + name;
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.