Service AJAX requests with webmethod in ASPX page

Flash picture Flash · Jan 23, 2012 · Viewed 13.2k times · Source

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 

Answer

Dave Ward picture Dave Ward · Jan 23, 2012

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.