2

I tried a simple web service (just a test if the value will p0pulate on the JavaScript code). I tried a very simple snippet but then it returns 'undefined'. Please advise. I tried some solutions but no luck.

Here a simple code on asmx file

[WebMethod]
public string HelloWorld(string param1, string param2)
{
   return "Hello World" + param1 + ":" + param2;
}

Here is the code on my javascript.

$.ajax({
   url: "SimpleService.asmx/HelloWorld",
   type: "POST",
   data: {
      'param1': 'value1',
      'param2': 'value2'
   },
   success: function(response) {
      alert(response.d);
   }
});

I tried getting the results using response.text and response.value and I'm still getting an undefined value.

success: function(response) {
      alert(response.text);
      alert(response.value);
   }

On my asmx file, I tried also replacing [WebMethod] to.

[WebMethod(EnableSession = true)]
[ScriptMethod(ResponseFormat = ResponseFormat.Json)]
public string HelloWorld(string param1, string param2)
{
   return "Hello World" + param1 + ":" + param2;
}

Please advise what is the correct format for getting the result from my web service.

Thank you

  • This is a related question [How to call webmethod in Asp.net C#](https://stackoverflow.com/questions/19110170/how-to-call-webmethod-in-asp-net-c-sharp) and there are probably many others similar to your question and already answered. – Cleptus Jul 10 '19 at 11:34

1 Answers1

0

You should put [ScriptService] attribute to your service class as below

[ScriptService]
public class SimpleService : System.Web.Services.WebService

After that, change your ajax call. Put contentType and change data as below:

    $.ajax({
        url: "SimpleService.asmx/HelloWorld",
        type: "POST",
        contentType: "application/json; charset=utf-8",
        data: "{ param1: 'value1', param2: 'value2' }",
        success: function (response) {
            alert(response.d);
        }
    });
Burak
  • 186
  • 9