Service AJAX requests with webmethod in ASPX page
Asked Answered
G

2

5

I am trying to service AJAX requests with a method in my .aspx page. For some reason I am not getting the data returned that I want. Can anybody tell me what I am doing wrong?

mypage.aspx:

<%@ Page Language="VB" Title="My Page" %>
<%@ Import Namespace="System.Web.Services" %>
<%@ Import Namespace="System.Collections.Generic" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<script runat="server">

    Protected Sub Page_Load(sender As Object, e As System.EventArgs)

    End Sub

    <WebMethod()> Public Function testmethod() As Integer
        Return 5
    End Function

</script>

<html>
<!--...rest of page including mybutton and myresults-->

JQuery:

$("#mybutton").click(function() {
    $.ajax({
      type: "POST",
      url: "mypage.aspx/testmethod",
      data: "{}",
      contentType: "application/json; charset=utf-8",
      dataType: "json",
      success: function(msg) {
        alert("success");
        $("#myresults").html(msg.d);
      },
      error: function(msg) {
        alert("error:" + JSON.stringify(msg));
      }
    });
});

When I click mybutton I get an alert "error:" and then whole lot of HTML that says:

Unknown web method testmethod.
Parameter name: methodName 
Granville answered 23/1, 2012 at 2:22 Comment(0)
V
12

The method needs to be Shared:

<WebMethod()> Public Shared Function testmethod() As Integer
    Return 5
End Function

Also, I'm not sure that page methods are supported when you don't use a code-behind file.

Vizor answered 23/1, 2012 at 2:52 Comment(1)
To add - In C# - it needs to be staticPlectron
C
0

What is the error that is being passed back?? The reason you are seeing the whole html page is because you have an error in the code and the msg that is being passed back is the full html which tells you where the error is. I'm sure if you fix the error then you would be fine.

I'm not sure if you are expecting to see the error message from the codebehind. Remember - the success or error functions being called in the Ajax section are called depending on whether the webservice method was called successfully or not. I think you are thinking that you will see the error message from teh webmethod here, but in reality, if the webmethod is throwing the error then you would still have a successful ajax call and thus the "success" function would be the one running. The "error" function will only run when the whole webmethod call fails, so there is no response from the server.

Hope that makes sense.

Combo answered 23/1, 2012 at 2:31 Comment(1)
Thanks I realised this after I posted, I have included the error message at the bottom of the question.Granville

© 2022 - 2024 — McMap. All rights reserved.