简体   繁体   中英

AJAX call not returning JSON object from WebMethod

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.

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 ;-)

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;
            }
        }
    }
}

**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!")
        }
     });

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