简体   繁体   中英

Error 500 when I try to call a simple method from ajax

I'm building a simple aspx page with a single controller.

This is the code of aspx page:

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="WebApplication1.Default" %>

<%

%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" >
    <head>
        <script src="https://cdn.zingchart.com/zingchart.min.js"></script>
        <script>
            zingchart.MODULESDIR = "https://cdn.zingchart.com/modules/";
            ZC.LICENSE = ["569d52cefae586f634c54f86dc99e6a9", "ee6b7db5b51705a13dc2339db3edaf6d"];
        </script>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
      <link href="https://fonts.googleapis.com/css?family=Roboto" rel="stylesheet">

</head>

<body>
    <div id="container">

        <div id="myChart"></div>
    </div>
     <div id="container1">
        <button id="clear">Clear</button>
        <button id="stop">Stop</button>
        <button id="start">Start</button>
      </div>
    <script>
    var myConfig = {
      //chart styling
      type: 'line',
      globals: {
        fontFamily: 'Roboto',
      },
      backgroundColor: '#fff',
      title: {
        backgroundColor: '#1565C0',
        text: 'ECG Real Time',
        color: '#fff',
        height: '30x',
      },
      plotarea: {
        marginTop: '80px'
      },
      crosshairX: {
        lineWidth: 4,
        lineStyle: 'dashed',
        lineColor: '#424242',
        marker: {
          visible: true,
          size: 9
        },
        plotLabel: {
          backgroundColor: '#fff',
          borderColor: '#e3e3e3',
          borderRadius: 5,
          padding: 15,
          fontSize: 15,
          shadow: true,
          shadowAlpha: 0.2,
          shadowBlur: 5,
          shadowDistance: 4,
        },
        scaleLabel: {
          backgroundColor: '#424242',
          padding: 5
        }
      },
      scaleY: {
        guide: {
          visible: false
        },
        values: '0:100:25'
      },
      tooltip: {
        visible: false
      },
      //real-time feed
      refresh: {
        type: 'feed',
        transport: 'js',
        url: 'feed()',
        interval: 500
      },
      plot: {
        shadow: 1,
        shadowColor: '#eee',
        shadowDistance: '10px',
        lineWidth: 5,
        hoverState: {
          visible: false
        },
        marker: {
          visible: false
        },
        aspect: 'spline'
      },
      series: [{
        values: [],
        lineColor: '#2196F3',
        text: 'Blue Line'
      }, {
        values: [],
        lineColor: '#ff9800',
        text: 'Orange Line'
      }]
    };

    zingchart.render({
      id: 'myChart',
      data: myConfig,
      height: '100%',
      width: '100%'
    });

    //real-time feed random math function
    window.feed = function(callback) {

        $.ajax({
        type: "POST",
        url: "Default.aspx/RefreshChartEcg",
        //data: '{name: "' + $("#<%=txtLastID.ClientID%>")[0].value + '" }',
        data: '10',
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (response) {
            var tick = {};
            tick.plot0 = response.d;
            tick.plot1 = parseInt(10 + 90 * Math.random(), 10);
            callback(JSON.stringify(tick));
        },
        failure: function(response) {
            alert(response.d);
        }
    });

      /*$.ajax({
          type: "POST",
          url: "Default.aspx/OnSubmit",
          data: "",
          error: function (XMLHttpRequest, textStatus, errorThrown) {
              //alert("Request: " + XMLHttpRequest.toString() + "\n\nStatus: " + textStatus + "\n\nError: " + errorThrown);
          },
          complete: function (jqXHR, status) {
              //alert("complete: " + status + "\n\nResponse: " + jqXHR.responseText);
              /*var tick = {};
              tick.plot0 = parseInt(10 + 90 * Math.random(), 10);
              tick.plot1 = parseInt(10 + 90 * Math.random(), 10);
              callback(JSON.stringify(tick));
          }
          success: Repaingchart
      });*/

        function OnSuccesss(response) {
          alert(response.d);
      }




    };
    //clear start stop click events
    document.getElementById('clear').addEventListener('click', clearGraph);
    document.getElementById('start').addEventListener('click', startGraph);
    document.getElementById('stop').addEventListener('click', stopGraph);

    function clearGraph() {
      zingchart.exec('myChart', 'clearfeed')
    }

    function startGraph() {
      zingchart.exec('myChart', 'startfeed');
    }

    function stopGraph() {
      zingchart.exec('myChart', 'stopfeed');
    }
  </script>
    <form id="form1" runat="server">
    <div>
        <asp:Label runat="server" id="HelloWorldLabel"></asp:Label>
         <asp:TextBox ID="txtLastID" runat="server"></asp:TextBox>
    </div>
    </form>
</body>
</html>

This is my controller of page:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web.Services;

namespace WebApplication1
{
    public partial class Default : System.Web.UI.Page
    {
        private OmniacareDiabesityDataProductionEntities db = new OmniacareDiabesityDataProductionEntities();

        protected void Page_Load(object sender, EventArgs e)
        {
            HelloWorldLabel.Text = "Pippo e pluto";
           // string variabile = "pluto";
        }

        [WebMethod]
        public static string RefreshChartEcg(string lastID)
        {
            /**
             * qui devo recuperare il codice per recuperare le informazioni real time dal database
             * */
            int lastIntID=0;
            if (lastID != "")
                lastIntID = Int32.Parse(lastID);

            return "";
        }
    }
}

Now, if I try to start my simple application, I can see this error of web browser console:

POST http://localhost:29319/Default.aspx/RefreshChartEcg 500 (Internal Server Error)

But if I try to start a debugger on RefreshCartEcg the control of debug not pass at the line code

In Ajax call, Can you try passing the data in json format as like below,

data : {lastID : "10"}

The problem seems in data that you have passed ajax to Web method. Please refer the answer that already given on this link

Ajax method should have below format:

data: "{ 'lastID': '10' }" 

OR

data: "{ lastID: '10' }"

There probably are two errors:

Firstly, in the ajax call, like said by vikscool, Jitendra Rangpariya and Gopal M, you should give a JSON object as data.

Secondly, you have to open that JSON, before you process the number

public static string RefreshChartEcg(string data)
    {
        /**
         * qui devo recuperare il codice per recuperare le informazioni real time dal database
         * */
        int lastIntID=0;

        if (data != "")
            json = JsonConvert.SerializeObject(data)
            lastIntID = Int32.Parse(json.lastID);

        return "";
    }

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