Search code examples
javascriptc#asp.netwebmethodpagemethods

ASP.NET PageMethod onSuccess function returns a HTML String


This is weird. My onSuccess() function in the javascript file returns a massive HTML Code of my entire web page instead of the value I actually return from my C# WebMethod

1) I am running Visual Studio 2015 on Windows 10

2) When debugged, I kept a breakpoint at the SignupAccount C# method. The breakpoint was not hit. It didn't get to that point. BUT the onSuccess function was called

Here's an explanation:

ASP.NET Web Form's HTML:

<html xmlns="http://www.w3.org/1999/xhtml">
 <head runat="server">
   <!--Code-->
 </head>
 <body class="account2 signup" data-page="signup">
   <!--Code-->
   <form id="form1" runat="server">
        <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"></asp:ScriptManager>

    <input type="text" name="firstname" id="firstname" placeholder="First Name" required autofocus>

    <input type="text" name="lastname" id="lastname" placeholder="Last Name" required autofocus>

    <button type="submit" onclick="signup()" id="submit-form" class="btn btn-lg btn-dark btn-rounded" data-style="expand-left">Sign In</button>

    <script src="JS/Account.js"></script>
   </form>
 </body>
</html>

WebMethod in C# Code Behind:

[WebMethod]
public static string SignupAccount(string fname, string lname)
{
    return "OK";
}

Javascript:

function signup() {
    var fname = document.getElementById("firstname").value;
    var lname = document.getElementById("lastname").value;

    PageMethods.SignupAccount(fname, lname, onSuccess, onFailure);

    function onSuccess(val) {
       alert(val);
       //Technically, this should display "OK". But instead it displays a HTML String 
       //of my entire Web Page starting from the <html> tag to the end
    }

    function onFailure() {}
}

Why is it happening? I believe the procedure and the code is correct. Is this something to do with Visual Studio?

EDIT

This is the response I get from the onSuccess function

http://pastebin.com/6MjAFPY9


Solution

  • For me, the problem was in my App_Start/RouteConfig.cs.

    1. Remove
    settings.AutoRedirectMode = RedirectMode.Permanent;
    
    1. If routes.EnableFriendlyUrls(settings); is in there too, add PageMethods.set_path to the JavaScript file, before your WebMethod call:
    ...
    
    PageMethods.set_path("YourPage.aspx");
    PageMethods.SignupAccount(fname, lname, onSuccess, onFailure);
    
    ...
    

    The answer is puzzled together from: