hlh3406 hlh3406 - 1 month ago 5
Ajax Question

Ajax never calls my .NET method?

Hi I have the following AJAX which references a method in my .aspx page. I've done some console debugging and my data.d is always undefined. So I've put a breakpoint in the .aspx page on the first line of the method referenced and it never hits it.

I'm really stuck - so if someone could point me in the right direction that would be great.

AJAX:

var param = { "mySearchString": str };
$.ajax({
type: 'POST',
url: 'myForm.aspx/myMethod',
data: JSON.stringify(param),
contentType: 'application/json; charset=utf-8',
dataType: 'json',
async: false,
success: function (data) {
$("#MyResults").empty();
console.log(data);
console.log(data.d);
console.log(data.d.length);
for (i = 0; i < data.d.length; i++) {
$("#MyResults").append("<li><a href='#' onClick='SetName(this)'>" + data.d[i].title + "</" + " a>" + "</" + "li>");
}
if (data.d.length == 0)
{
$("#MyResults").empty();
}
}
});


The initial set up for my .NET method:

[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
[WebMethod(EnableSession = true)]
public static IEnumerable<MyItem> myMethod(string searchString)
{


I'm passing the right type across, and there are no errors on build or when I run it. So I'm a bit stumped!

Answer

I found my answer here: ASP.NET Calling WebMethod with jQuery AJAX "401 (Unauthorized)"

I was hitting this error:

Object {Message: Ajax error: "Authentication failed.", StackTrace: null, ExceptionType: "System.InvalidOperationException"}

Turns out that I needed to do:

Inside ~/App_Start/RouteConfig.cs change:

settings.AutoRedirectMode = RedirectMode.Permanent;

To:

settings.AutoRedirectMode = RedirectMode.Off;

Hopefully this will help someone else!