0

I have the following page method in the file default.aspx.vb, using .NET 2.0:

<WebMethod()> _
Public Shared Function GetStatisticData(ByVal userId As Integer) As JavaScriptSerializer
    Dim stats As JavaScriptSerializer = New JavaScriptSerializer()

    stats.Serialize(statBiz.GetAllSaleStatistics(userId))

    Return stats
End Function

And in default.aspx

opt.ajax({
    type: "POST",
    url: 'default.aspx/GetStatisticData',
    data: "{userId: 6601}",
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (data) {
        console.log(data);
    },
    error: function (request, status, error, response) {
        console.log(error);
    }
});

But the method in the codebehind file does never get hit and i get this error from the console log:

SyntaxError: Unexpected token < in JSON at position 2
    at JSON.parse (<anonymous>)
    at n.parseJSON (jquery-1.12.4.min.js:11)
    at Xb (jquery-1.12.4.min.js:11)
    at y (jquery-1.12.4.min.js:11)
    at XMLHttpRequest.c (jquery-1.12.4.min.js:11)

Can somebody tell me what I am missing here?

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
Martin Overgaard
  • 355
  • 2
  • 7
  • 21

2 Answers2

1

Can somebody tell me what I am missing here?

For starters your return type should be the return type of statBiz.GetAllSaleStatistics and should return the result of that call. You do NOT need to spin up a serializer yourself and there is no need to tie yourself to returning JSON when the Framework is capable of determining which serializer to spin up based on the request headers. You certainly shouldn't try to return a JavaScriptSerializer.

This sample code and output should demonstrate why returning the serializer won't work:

Dim js = New JavaScriptSerializer()
js.Serialize(New List(Of Int32) From { 1, 2, 3})
Console.WriteLine(New JavaScriptSerializer().Serialize(js))

{"MaxJsonLength":2097152,"RecursionLimit":100}

That's not a serialized list! It's a serialized serializer!


Let's say for the purpose of illustration that statBiz.GetAllSaleStatistics(userId) returns an instance of a SaleStatistics class. Please try the following but of course replace SaleStatistics with your actual type:

<WebMethod()> _
Public Shared Function GetStatisticData(ByVal userId As Integer) As SaleStatistics
    Return statBiz.GetAllSaleStatistics(userId)
End Function

This in itself will likely not wholly resolve your issue. I have a suspicion that your method is returning XML and that being a legacy app there may be entries missing from web.config. You may also need to target .NET Framework 3.5.

Stephen Kennedy
  • 20,585
  • 22
  • 95
  • 108
  • I return a list of Statistic but my method is never hit when i run in debug mode and when I tjek the result of error and response I get 1. parsererror Error : SyntaxError: Unexpected token < in JSON at position 2 2. undefined – Martin Overgaard Feb 21 '18 at 09:31
0

Webmethods are used by webservices, not web applications. You install the webservice on a server and call (SOAP) the webservice in your code after adding the web service as a service. The extension for a webservice file is .asmx. Web services are kind of dated (.NET Framwork 2.0 to 3.5) and most folks use RESTful api's. To create a web service go to File --> New -->Asp.Net Empty Web application. on that Right click --> Add New item - >webservice template.

Now if you do not like that answer and still want to use your code, remove the webmethod_ from your code and in javascript you can assign the results of the call to a variable using '<%= GetStatisticData(SomeVariableStoringUserID) %>' passing in the userid you're querying.

UPDATE: Seems as if I'm behind the times a bit, to say the least. So @Stephen Kennedy answer would seem to be the correct one in this context. Your method returns JavaScriptSerializer when I think you're expecting a json document.

Prescott Chartier
  • 1,519
  • 3
  • 17
  • 34
  • I think you've got the wrong end of the stick here :) He has a page method, which is a web method declared in code behind. It's almost identical to asmx except the method is declared as static/shared in the .aspx.vb. He is calling the web method with a jQuery Ajax call. Page methods are capable of returning JSON when properly configured and called correctly. Yes this is legacy tech, but it is something that ought to work. Moving to asmx likely won't make any difference, and the inlining suggestion is irrelevant here as this is not webform output but an Ajax call. – Stephen Kennedy Feb 20 '18 at 13:00
  • I'm not familiar with Ajax so I cannot comment. I'm a tad old school but I've never seen a webmethod used in this context anywhere. It has always been my understanding that webmethods are called via SOAP, I do not see any indication that SOAP is in use here. – Prescott Chartier Feb 20 '18 at 13:10
  • The JSON capabilities were retro-fitted by Microsoft (in Framework 3.5 from the best I can tell/remember). [Call an ASP.NET C# Method (Web Method) Using JQuery](http://www.c-sharpcorner.com/UploadFile/63e78b/call-an-Asp-Net-C-Sharp-method-web-method-using-jquery/) is a nice intro. We have this in production use alongside some SOAP and a growing ASP.NET Web API and we're far from alone in that. – Stephen Kennedy Feb 20 '18 at 15:45
  • Thanks for the info, I do admit I'm a tad behind with all the latest techniques. Last 10 years of my career was as a Systems Engineer and I've been retired for 2 years. So I'm behind just a little ... lol ... – Prescott Chartier Feb 20 '18 at 15:51
  • Calling the method directly works just fine, but as I need to call this with ajax it has to work that way ;o) – Martin Overgaard Feb 21 '18 at 09:13