Search code examples
asp.netajaxasp.net-ajax

Adding Ajax to aspx pages


I am working with a very large project that is running on ASP.NET framework. I am trying to add some new functionality to make the application more userfriendly and I need to use ajax. I have used ajax in MVC applications ect but I keep getting errors with aspx. I know this is an older language but upgrading the application is not possible at this time.

I have read other posts and it seems like it is doable but I am getting error 404. The below is code I have copied and changed for my testing. Could someone help with what is wrong ?

    [WebMethod(enableSession: true)]
    public static void BtnAddCoin(int coin)
    {

        var t = coin;

    }

/////////////////////////////////////////////////////

        var coin = 1;
        $.ajax({
            type: "POST",
            url: "/Product_AddUpdate.aspx/BtnAddCoin",
            data: JSON.stringify({ coin: coin }),
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: function () {
                alert("AddCoin");
            },
            error: function (req, status, error) {
                alert("x" + error + status);
            }
        });

Solution

  • What you have looks close.

    Remove the "/" in your ajax call.

    Hence try this:

    url: "Product_AddUpdate.aspx/BtnAddCoin",
    

    Also, if you have friendly URLs turned on, then you need in RouteConfig.cs need to change this:

    settings.AutoRedirectMode = RedirectMode.Permanent;
    
    
    to:
    
    settings.AutoRedirectMode = RedirectMode.Off;
    

    Try both of the above, and your call should work just fine.

    Of course, you do have jQuery correctly installed and available?

    Last, but not least? Try clearing your browser cache, as during testing, if you used the wrong URL, often it will become cached, and calls don't work.

    So, try all 3 of the above:

    Remove the "/".
    Change RedirectMode to off.
    Clear your browser cache.