Search code examples
javascriptc#asp.netajaxwebmethod

ASP.NET Web Forms [WebMethod] not being called by AJAX Post


I'm working on a ASP.NET Web Forms project using bootstrap/jquery 3.4.1 js. I'm having an issue of getting my AJAX Post working. It's supposed to hit my [WebMethod] within Schedule.aspx, but it's not. I've put down a breakpoint on it and it's never activated when clicking the save button. The AJAX succeeds and the alert pops up, and I've already verified that the stringify data is outputting as expected, but why is it not hitting the [WebMethod]?

Here's my JavaScript function:

$(document).on('click', '#modalSave', function (e) {
     
    var testValue = "TestValue";

    $.ajax({
        type: "POST",
        url: "Schedule.aspx/InsertItem",
        data: JSON.stringify({ Content: testValue }),
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function ()
        {
            alert("AJAX success");
            $('#DetailsModal').modal('hide');
        }
    })
});

My [WebMethod]

using System.Web.Services;

namespace Scheduler
{
    public partial class Schedule : Page
    {
        [WebMethod]
        public static string InsertItem(string Content)
        {
            return Content;
        }
    }
}

My Modal and Save Button:

<div id="DetailsModal" class="modal fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;  </button>
                <h4 class="modal-title" id="myModalLabel">Modal title</h4>
            </div>
            <div class="modal-body">
                <textarea id="modalTextArea" style="width: 100%; height: 300px;"></textarea>
            </div>
            <div class="modal-footer">
                <button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
                <button id="modalSave" type="button" class="btn btn-primary">Save changes</button>
            </div>
        </div>
    </div>
</div>

Solution

  • I have simulated your code and I can successfully enter the breakpoint of the WebMethod, one possible reason is that you do not have debugging mode activated in your Visual Studio IDE

    enter image description here

    enter image description here

    UPDATE 2:

    Enable calls to WebMethod with RouteConfig configuration:

    public static class RouteConfig
    {
        public static void RegisterRoutes(RouteCollection routes)
        {
            var settings = new FriendlyUrlSettings();
            settings.AutoRedirectMode = RedirectMode.Off;
            routes.EnableFriendlyUrls(settings);
        }
    }