Call ASP.NET PageMethod/WebMethod with jQuery - returns whole page
Asked Answered
D

8

37

jQuery 1.3.2, ASP.NET 2.0. Making an AJAX call to a PageMethod (WebMethod) returns the full/whole page instead of just the response. A breakpoint on the page method shows it's never getting hit. I have the [WebMethod] attribute on my method, and it is public static, returns string and accepts no params. I even tried adding [ScriptService] at the top of my class to see if it helped, but it did not.

I have seen this post Jquery AJAX with ASP.NET WebMethod Returning Entire Page which had my same symptoms, but I am still having a problem. I read http://encosia.com/2008/05/29/using-jquery-to-directly-call-aspnet-ajax-page-methods/ and I feel like I'm following this to the T, but still no luck.

The jQuery call I'm making is:

jQuery.ajax({
    type: 'POST',
    contentType: 'application/json; charset=utf-8',
    data: '{}',
    dataType: 'json',
    url: 'MyPage.aspx/SomePageMethod',
    success: function(result){
        alert(result);
    }
});

The request/response headers, as per Firebug in FF3, are as follows

Response Headers
Server  ASP.NET Development Server/8.0.0.0
Date    Tue, 24 Feb 2009 18:58:27 GMT
X-AspNet-Version    2.0.50727
Cache-Control   private
Content-Type    text/html; charset=utf-8
Content-Length  108558
Connection  Close

Request Headers 
Host    localhost:2624
User-Agent  Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.0.6) Gecko/2009011913 Firefox/3.0.6
Accept  application/json, text/javascript, */*
Accept-Language en-us,en;q=0.5
Accept-Encoding gzip,deflate
Accept-Charset  ISO-8859-1,utf-8;q=0.7,*;q=0.7
Keep-Alive  300
Connection  keep-alive
Content-Type    application/json; charset=utf-8
X-Requested-With XMLHttpRequest
Referer http://localhost:2624/MyApp/MyPage.aspx
Content-Length  2
Cookie  ASP.NET_SessionId=g1idhx55b5awyi55fvorj055; 

I've added a ScriptManager to my page just for kicks to see if it helped, but no luck there.

Any suggestions?

Derbent answered 24/2, 2009 at 19:6 Comment(0)
A
28

Do you know that Page Methods are working properly? If you use the the ScriptManager do they work?

It sounds like you might be missing a web.config entry. Specifically the HttpModules section.

Arsenide answered 24/2, 2009 at 19:22 Comment(3)
Dangit! I knew it was going to be something easy. I guess I assumed that any configs that would be needed would've been handled by VS when I dropped in a ScriptManager (which was why I added it, cause I knew you don't need it. Thanks!Derbent
Been researching this problem for an hour+ and web.config and the ScriptModule httpModule ended up being the culprit. Thanks!Hypogeous
Hi Dave. Per @Surya, that link doesn't appear to work anymore.Derbent
B
24

I was missing one line from my web.config:

<system.web>
  <httpModules>
    <add name="ScriptModule" type="System.Web.Handlers.ScriptModule, System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"/>
  </httpModules>
</system.web>
Boynton answered 15/4, 2009 at 17:25 Comment(2)
Adam Seabridge, where ever you are now, I love you.Masto
This solution introduces a new error : HTTP Error 500.22 - Internal Server ErrorEugine
D
13

I encountered this problem again today for a different reason: I had misspelled "application" in

contentType: 'application/json'

And was getting a full-page response instead of a call to the WebMethod.

Derbent answered 16/6, 2010 at 14:26 Comment(0)
S
7

If you have tried all that and still get the whole page returned from your pagemethod, you may want to make sure you are not using friendly urls. If you are using them, this trick may help you

Add this line on your js script before you make the call:

PageMethods.set_path(PageMethods.get_path() + '.aspx');
Susurrant answered 8/8, 2014 at 18:28 Comment(2)
In addition to this, because of using FriendlyURLs I had to add this https://mcmap.net/q/426257/-jquery-pagemethods-401-authentication-failed-with-friendlyurlsChitin
This is what I needed as well. I have no web.config modules. Instead of doing what @Chitin suggested, I just removed the line settings.AutoRedirectMode = RedirectMode.Permanent;Anastatius
K
1

Throwing this out here as a side note. I was getting that error due to the length of my string variables in my HTML string and the website I used to get my ajax called looked like this.

loc = (loc.substr(loc.length - 1, 1) == "/") ? loc + "Default.aspx" : loc;
        $.ajax({
            type: "POST",
            url: loc + "/" + methodName,
            data: "{" + args + "}",
            contentType: "application/json; charset=utf-8",
            dataType: "json",
            success: onSuccess,
            error: onFail
        });

It wasn't capable of extracting the .aspx link correctly, so I just hardcoded my webpage instead of using the loc var.

Knop answered 15/2, 2011 at 5:58 Comment(0)
D
1

Commenting the following line in RouteConfig.cs works for me

 settings.AutoRedirectMode = RedirectMode.Permanent;
Drawplate answered 10/4, 2019 at 15:27 Comment(0)
M
0

Most ajax scenarios I've seen really should call a web service or separate script handler, not a page. That is extremely easy to do in .net 3-5, not so easy in 2-0. Even after you figure out (if) how not to load the whole page, here are reasons not to call a page method:

1) The page method might load less stuff than a full page load, but still far more than you need for a simple ajax call. 2) Lousy separation of responsibilities. The page is probably responsible for nicely laying stuff out, not the logic you are using in the ajax method.
3) Maybe you need some session state, but that should still be available.

I'm currently updating my knowledge on this subject ... I'll look for a good answer to this question in this thread, or I'll post one next week. Here is the direction I am headed

1) Send JSON from server to client, and use javascript to update your page. - a variety of frameworks make it easy to produce JSON from the web server.
2) JQuery makes ajax calls, json handling, and client formatting fun, instead of painful.

Mechanist answered 25/2, 2009 at 7:16 Comment(4)
That's what a "page method" is. It's just a convenient way of writing a web service that returns JSON.Arsenide
1) It's still just an async javascript call. A PageMethod, also known as a public static method decorated with a WebMethod attribute in your code behind, is just syntactic sugar for telling ASP.NET to respond to POST requests against that address with a response from the code.Derbent
(cont) The response is still just JSON, and very small. No viewstate, even. 2) How do you know what logic I am using in the page method? In my case, it is simply grabbing data that is in fact specific to this page, but was not available when the page loaded. 3) I didn't need session, but theDerbent
(cont) async call works fine with session - your request is still attached to your cookie. other #1) Yes, that is why I am using jQuery.ajax() ;) other #2) Indeed, jQuery is wonderfulDerbent
B
0

After almost two hours and after had tried everything i finally solved it.@Marvin Zumbado's comment helped me.I was missing the .aspx from my url.I know this is not my best moment as a programmer!

Brophy answered 29/11, 2017 at 17:47 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.