简体   繁体   中英

Uncaught Reference Error: function is not defined (ASP.NET)

I'm teaching myself how to work with ASP.NET, and I'm trying to call a C# function in a JS function in my .aspx file.

Here's my JS section:

<script type="text/javascript">
        function Run() {
        alert("Running!")
        var ranking = parseInt(document.getElementById("rank").value);
        var collsize = parseInt(document.getElementById("size").value);
        var collsafety = 
           parseInt(document.getElementById("safety").value);
        var best = PageMethods.Survey(ranking, collsize, collsafety);
        document.write(best);
    }
</script>

The signature of the C# function (it's embedded in the .aspx file like the JS function):

<script language="c#">
    [System.Web.Services.WebMethod]
    public static string Survey(int ranking, int collsize, int 
       collsafety) {
       ....
    }

The exact error message is: Uncaught ReferenceError: PageMethods.Survey is not defined.

I'm calling the Run method with a button using onclick. I know the method is entered, because the first alert happens. However, when I try calling Survey, I get the error.

I've already read a couple of answers, like this: jquery PageMethod saying the method does not exist , but the suggested AJAX didn't work either. I also read this: https://www.codeproject.com/Questions/561226/errorpluspageMethodplusisplusundefined but I can't see what I'm not doing right...

Your code will not work since you are embedding the c# code directly on the aspx file. Embed it on the aspx.cs file instead:

protected void Page_Load(object sender, EventArgs e)
    {

    }

[System.Web.Services.WebMethod]
public static string Survey(int ranking, int collsize, int 
   collsafety) 
  {
     return "Hello";
  }

You can call it via PageMethods:

    <script type="text/javascript">

        function Run() {
        var ranking = 123;
        var collsize = 123;
        PageMethods.Survey(ranking, collsize, onSucess, onError);

        function onSucess(result) {
            alert(result);
        }

        function onError(result) {
            alert('Please contact administrator.');
        }
    }
</script>

Lastly don't forget to add ScriptManager on the calling Page (Default.aspx on my example) and enable PageMethods to True:

<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="True">
</asp:ScriptManager>

Here how it look like for further reference:

在此处输入图片说明

The code when I call the script on the button:

 <asp:Button ID="Button1" runat="server" Text="Button" OnClientClick="Run()" />

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM