How to get return value of WebMethod from JQuery

I am tryring to get the return value of WebMethod from JQuery call, but I am getting "undefined" message. Here is my code below

$.ajax({
        type: "POST",
        url: "Receipt/BarcodeEntered",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "text",
        success: function (msg) {
                    alert(msg.d); // This displays "Undefined"
                    alert(msg);   // This displays the whole html
                 }
});

and the WebMethod is below

[WebMethod]
public static string BarcodeEntered() 
{
    return "test_string";
}

how can I get the value from WebMethod and display it on client side?

Answers


WebMethod officialy only can return XML or JSON. Default is json, so whatever you return gets converted to json

change in JQuery dataType: "json",

$.ajax({
        type: "POST",
        url: "Receipt/BarcodeEntered",
        data: "{}",
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (msg) {
                    alert(msg);
                 }
});

and you should return class not single string. because string can not be converted valid json object.

public class SampleClass{
    public string Message {set; get;}
}

[WebMethod]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public SampleClass BarcodeEntered()
{

        return new SampleClass(){
        Message  = "Sample message"
    };

}

You need to return JSON, let me write down an example.

public JsonResult DoStuff()
{
    string text = "text";

    return Json(text, JsonRequestBehavior.AllowGet);
}

Here is the working demo I am using this in my asp.net page. The data is will be in d property.

JQuery code.

    $.ajax({
    type: "POST",
    url: "/Subfolder/MyPageName.aspx/myWebMethodName",
    data: '{}',
    contentType: "application/json; charset=utf-8",
    dataType: "json",
    success: function (msg) {
      if (msg.d == "OK") {
       alert("OK")
      } else {
         alert(msg.d);
      }
    }
   });

C# Code

[WebMethod]
public static string myWebMethodName()
{ 
   return "OK";
}

Need Your Help

How can I change the page programatically in CarouselPage in Xamarin.forms?

c# xamarin.ios xamarin.forms carousel c#-3.0

I'm using CarouselPage class to implement Horizontal Slider in Xamarin.Forms.