Seamy
Seamy

Reputation: 307

Getting 500 Internal Server Error when calling a WebMethod using ajax

I am having an issue hitting my C# WebMethod on the code behind and getting 500 internal server error. I don't really understand why it won't hit it so it would be really great if someone could tell me what is the problem.

enter image description here

So this is my ajax call and doesn't work even with data and datatype not commented out.

$('#chkBxAutoCost')
    .click(function(e) {
            $.ajax({
                type: "POST",
                url:   "BatchReportCriteriaSelection.aspx/GetAutoJsonBatches",
                contentType: 'application/json; charset=utf-8',
                dataType: 'json',
                data: "{}",
                error: function(XMLHttpRequest, textStatus,    errorThrown) {
                    console.log("Request: " +
                        XMLHttpRequest.toString() +
                        "\n\nStatus: " +
                        textStatus +
                        "\n\nError: " +
                        errorThrown);
                },
                success: function() { console.log("success") }
            });
        }
    );

And this is my code behind method of the page:

[WebMethod]
public string GetAutoJsonBatches()
{
    return autoJsonBatches;
}

So I have attached a breakpoint on this WebMethod and it's not being hit. I am pretty stuck so if someone had any insight I'd greatly appreciate it.

Upvotes: 1

Views: 2817

Answers (3)

M. Wiśnicki
M. Wiśnicki

Reputation: 6203

First you have edit RouteConfig.cs and use

settings.AutoRedirectMode = RedirectMode.Off;

Next edit your GetAutoJsonBatches() to static

They're static because they are entirely stateless, they don't create an instance of your page's class and nothing is passed to them in the request (i.e. ViewState and form field values).

HTTP is stateless by default, ASP.Net does a lot of stuff in the background with ViewState, Session, etc. during a standard page request to make life easier for developers.

Source

[WebMethod]
public static string GetAutoJsonBatches()
{
    return autoJsonBatches;
}

Upvotes: 1

Seamy
Seamy

Reputation: 307

So as botond said in the comments my problem was that webmethods need to be static! Thanks very much was really wrecking my head!

Upvotes: 1

Ali Bahrami
Ali Bahrami

Reputation: 6073

To allow this Web Service to be called from script, using ASP.NET AJAX, you need to use [System.Web.Script.Services.ScriptService] attribute for your WebService.

[System.Web.Script.Services.ScriptService]
public class WebService1 : System.Web.Services.WebService
{

    [WebMethod]
    public string GetAutoJsonBatches()
    {
        return autoJsonBatches;
    }
}

And you haven't provided us what exactly is the exception message.

Upvotes: 0

Related Questions