简体   繁体   中英

call function in 'code behind' with AJAX in ASP.NET WebForms?

I want to get access to a method in code behind when I clicked an span in my view aspx:

DEFAULT.ASPX VIEW CODE:

<asp:Content ID="BodyContent" ContentPlaceHolderID="MainContent" runat="server">
<%-- MY SPAN --%>
 <span runat="server" onclick="ShowChartSpider(this.id)" id="group_2" style="cursor: pointer" class="pull-right">My Span</span>


<%-- JAVASCRIPT CODE --%>
    <script type="text/javascript">
        function ShowChartSpider(group_id) {

            $.ajax({
                type: "POST",
                url: "Default.aspx/MethodToCreateChart",
                dataType: "json",
                data: "{'parameter1':" + JSON.stringify(group_id) + "}",
                contentType: "application/json; charset=utf-8",                

                success: function (data) {
                    alert("all correct");
                },
                error: function (data) {
                    alert("no");
                }
            }
            );
        }
    </script>
</asp:Content>

DEFAULT.ASPX.VB CODE BEHIND:

<WebMethod()>
    <ScriptMethod(ResponseFormat:=ResponseFormat.Json)>
    Public Shared Sub MethodToCreateChart(sender As Object, e As EventArgs)
        ' My code to create the chart .....
    End Sub

if I run the page, and inspects the page with the browser to see errors, none appear, but the code does not reach the breakpoint that I put in the method in codebehind.

What I´m doing wrong? I would appreciate suggestions, thanks.

First check your server allow non HTTPS request. i had that type of issue and my server didn't allow me to do that. it so then disable that and test.

Then check the response status.

error: function(xhr, status) {
alert(xhr.status); }

let us know that is the outcome.

--Ruhul

Go to "RouteConfig.vb" under "App_Start" folder.

Change following line

 settings.AutoRedirectMode = RedirectMode.Permanent

To

settings.AutoRedirectMode = RedirectMode.Off

i think your method code returning something like this.

Return Default.aspx/MethodToCreateChart

so me your MethodToCreateChart logic.

you can try with below sample method. your internal server error are coming because you are returning somethng from your method.

Public Shared Function MethodToCreateChart(parameter1 As String) As String

   Return "Hello " & Environment.NewLine & "The Current Time is: " & _DateTime.Now.ToString()
End Function

我认为您应该从span标记中删除“ runat = server”属性。

You use aspx file same as ashx files. So have a look at below links: 1. How do you debug ASP.net HTTPHandler 2. Can't debug ASHX handler

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