2

I am able to make it work (success callback).

But what i get in response is the whole HTML of default.aspx

The AJAX:

function CreateLottery(lottery) {
debugger; // 'lottery' comes with the properties of the Lottery class
$.ajax({
    type: 'POST',
    url: 'default.aspx/Create',
    data: JSON.stringify({ data: lottery }),
    dataType: 'text',
    success: function (data, status) {
        alert(data.TotalValue + " " + status) //"undefined success"
    },
    error: function () {
        alert("error!")
    }
 });
}

I get "undefined success" in the alert. "data" is the whole html document, not a "Lottery" object.

The Create WebMethod and the Lottery class:

[WebMethod]
public static Lottery Create(Lottery lottery)
{
    return lottery;
}
public class Lottery
{
    public string TotalValue { get; set; }
    public string Players { get; set; }
}

I can't figure out what is going on, the WebMethod is returning exactly the same object that it received, how i can't access it on the success callback?

EDIT: The WebMethod is not being hit. The "ScriptManager" is present in default.aspx with EnablePageMethods set to true. If i change the WebMethod name (Create) to anything and keep /Create in AJAX url still get the whole default.aspx HTML in response.

Tiago
  • 365
  • 1
  • 4
  • 17
  • Hint: complaining about downvotes is likely to only bring more downvotes. – John Dvorak Jul 09 '16 at 12:38
  • I removed it. Can't you help, instead of this unfriendly treatment? Perhaps your downvoting of a legitimate question is really going to help me. Thanks. – Tiago Jul 09 '16 at 12:40
  • 1
    I don't think it is working, the "whole document" is probably a 404 or 500 http response. Did you actually look at the contents of `data` ? – Crowcoder Jul 09 '16 at 12:44
  • @Crowcoder Yes i did, it is the whole html of the page, a 200 response. It's as if the WebMethod is not returning an object. – Tiago Jul 09 '16 at 12:48
  • I do what I find helpful. Is there a better way I could have worded my advice? Also, what makes you so sure I downvoted your question or that it was unfair? – John Dvorak Jul 09 '16 at 12:52
  • 1
    What is in the html? I'm trying to figure out if you have perhaps custom errors ON and you are not even hitting the webmethod. – Crowcoder Jul 09 '16 at 12:55
  • The html is the normal default.aspx page. If i'm not hitting the webmethod how i get a success callback? Thank you. – Tiago Jul 09 '16 at 12:58
  • 1
    A 200 response just means a response was generated and sent. It doesn't mean it is the response you expected. Put a break point in the web method and see if it is hit. – Crowcoder Jul 09 '16 at 13:03
  • Your suggestion was right, it never reaches the WebMethod. How is that possible? There's no typos, what can it be? – Tiago Jul 09 '16 at 13:14
  • [Maybe this SO question](http://stackoverflow.com/questions/6928533/calling-a-webmethod-with-jquery-in-asp-net-webforms) has your answer. – Crowcoder Jul 09 '16 at 13:22
  • I have EnablePageMethods=true set on a ScriptManager inside default.aspx ContentPlaceHolder element. It never reaches the WebMethod – Tiago Jul 09 '16 at 13:45
  • I just changed the WebMethod name to some random name and kept the url (/Create) in AJAX. I still get the whole HTML. – Tiago Jul 09 '16 at 14:10
  • As Crowcoder already said: Again, have a look at that html. You changed the uri, the result may differ. It might be the html of the error page generated by asp.net which might provide additional hints. – Jan Köhler Jul 09 '16 at 14:13
  • It isn't an error page. It is the whole normal html from default.aspx – Tiago Jul 09 '16 at 14:15
  • Ok. Then to narrow it down, give it another try ;) create another method which simply accepts an int and returns a string or whatever. Then see if that method is hit. If that fails, something very basically must be wrong and it's not related to the json serialization. – Jan Köhler Jul 09 '16 at 14:19
  • I created a similar webmethod that accept "string lottery" and returns it as "string". In AJAX data is a manual string. Still get the whole HTML in response. So i am seeing the HTML in more detail: http://pastebin.com/PL4HfSTH and i read there "ASP.NET Ajax client-side framework failed to load". – Tiago Jul 09 '16 at 14:55

3 Answers3

0

I think there are two things you'll have to consider:

First of all: You'll have to correct the content type header. It should be application/json instead of text.

The other issue is that [WebMethod] expects XML. It doesn't handle JSON out of the box.

To let your WebMethod return its contents formatted as JSON, you'll have to additionally decorate it as ScriptMethod. That attribute allows you to specify the format of the response as JSON.

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public static Lottery Create(Lottery lottery)
{
    // ...
}

Well, but there's one thing I'm not sure about: While you can specify the ResponseFormat I don't see a way to specify the RequestFormat. I assume it accepts JSON as request-type when you define it as response-type. But well, that's just an assumption. Give it a try ;-)

Jan Köhler
  • 5,817
  • 5
  • 26
  • 35
  • I tried everything you said, with no success. The problem seems to be that the WebMethod is never hit. The "ScriptManager" is present on default.aspx – Tiago Jul 09 '16 at 13:51
  • Too bad :( It might be a good idea to start fiddler in parallel to intercept the http traffic and see if that gives any additional hints. – Jan Köhler Jul 09 '16 at 14:07
  • I just changed the WebMethod name to some random name and kept the url (/Create) in AJAX. I still get the whole HTML. – Tiago Jul 09 '16 at 14:09
  • Unfortunately not. With the simplest data possible (just a string) i still get the whole document. I have the ScriptManager. The callback is success. What am i missing? I can't believe i am stuck in this. This is the HTML: http://pastebin.com/PL4HfSTH – Tiago Jul 09 '16 at 14:58
0

We can't tell why it is not working for you, but perhaps you could try another approach. [WebMethod] is pretty hacky in my opinion, and apparently more complicated than in needs to be. You could add a WebAPI service to your project, but if you want to stick with "old school" web forms then you can implement an IHttpHandler as an ashx file that is a "web service". Note that .aspx pages also implement IHttpHandler but they are designed to return HTML while handlers are meant for generic request handling like file downloads, and data like xml and json.

Implement something like this with the Handler item template and hit it with your ajax call:

using System.IO;
using System.Web;

namespace WebApplication1
{
    public class LotteryHandler : IHttpHandler
    {
        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "application/json";

            using (var reader = new StreamReader(context.Request.InputStream))
            {
                string values = reader.ReadToEnd();

                //Use Newtonsoft to deserialize to Lottery type

                //do whatever with Lottery

                //Use Newtonsoft to serialize Lottery again (or whatever you want to return)

                context.Response.Write(your_serialized_object);

                //finish the response
                context.Response.Flush();
                HttpContext.Current.ApplicationInstance.CompleteRequest();
            }
        }

        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}
Crowcoder
  • 11,250
  • 3
  • 36
  • 45
0

**old code **

$.ajax({
    type: 'POST',
    url: 'default.aspx/Create',
    data: JSON.stringify({ data: lottery }),
    dataType: 'text',
    success: function (data, status) {
        alert(data.TotalValue + " " + status) //"undefined success"
    },
    error: function () {
        alert("error!")
    }
 });

**New code **

see the content type and datatype change here

 $.ajax({
        type: 'POST',
        url: 'default.aspx/Create',
        data: JSON.stringify({ data: lottery }),
     contentType: "application/json; charset=utf-8",
       dataType: "json",
       success: function (data, status) {
            alert(data.TotalValue + " " + status) //"undefined success"
        },
        error: function () {
            alert("error!")
        }
     });
Sundara Prabu
  • 2,361
  • 1
  • 21
  • 20