Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call WebMethod?

I am trying to call a WebMethod from JavaScript. So far I have:

The EMSWebService.asmx:

namespace EMSApplication.Web.WebServices
{
    /// <summary>
    /// Holds the Webservice methods of EMSApplication
    </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]     
    [System.Web.Script.Services.ScriptService]
    public class EMSWebService : System.Web.Services.WebService
    {
        [WebMethod]
        public string HelloWorld()
        {
            return "Hello World";
        }
    }
}

In the aspx page I have added the followings:

<asp:ScriptManager ID="ScriptManager" runat="server">
    <Services>
        <asp:ServiceReference Path="~/WebServices/EMSWebService.asmx" />
    </Services>
</asp:ScriptManager>
<input onclick="callWebMethod();" id="btn" type="button" value="Click Me" />

And the JavaScript is:

<script type="text/javascript">
    function callWebMethod() {
        EMSApplication.Web.WebServices.EMSWebService.HelloWorld(OnComplete, OnError);            
    }

    function OnComplete(result) {
        alert(result);
    }

    function OnError(result) {
        alert(result.get_message());
    }

</script>

But the method is not executing. I am getting following JavaScript error:

EMSApplication not defined.

Is there anything I am missing? Do I need to do some other configuration?

The Project structure is depicted below:

enter image description here

JavaScript and components is in Login.aspx.

Is there any significance of the URL of [WebService(Namespace = "http://tempuri.org/")]


Edit:

I have also tried this by using jQuery and modify the aspx page as:

$(document).ready(function () {
        $("#btn").click(function () {                
            $.ajax({
                type: "POST",
                url: "../WebServices/EMSWebService.asmx/HelloWorld",
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (response) {
                    alert(response.d);                        
                },
                failure: function (msg) {                        
                    alert(msg.d);
                }
            });
            return true;
        });
    });

I have written System.Diagnostics.Debug.WriteLine("Hello World"); inside the WebMethod, it is executing that i.e., it is printing "Hello World" in the Output Window of the Visual Studio but I am not getting any alert message.

like image 636
Tapas Bose Avatar asked Mar 24 '12 17:03

Tapas Bose


People also ask

What is WebMethod in C#?

The WebMethod attribute is added to each method we want to expose as a Web Service. ASP.NET makes it possible to map traditional methods to Web Service operations through the System. Web. Services. WebMethod attribute and it supports a number of properties that control the behavior of the methods.

Why is WebMethod static?

They're static because they are entirely stateless, they don't create an instance of your page's class and nothing is passed to them in the request (i.e. ViewState and form field values). HTTP is stateless by default, ASP.Net does a lot of stuff in the background with ViewState, Session, etc.


2 Answers

I wanted to answer the question directly.

I have a WebMethod, sitting in a SomePage.aspx file:

[WebMethod]
public static String DoSomething(String shiftName)
{
    return shiftName+" hi there";
}

The question is: How do i call this web method? Since this is HTTP, the answer is to to an HTTP POST to the server:

POST http://localhost:53638/SomePage.aspx/DoSomething HTTP/1.1
Accept: text/html, application/xhtml+xml, */*
Accept-Language: qps-ploc,en-US;q=0.5
Accept-Encoding: gzip, deflate
Host: localhost:53638
Connection: Keep-Alive
Content-Length: 23
Content-Type: application/json;charset=utf-8

{'shiftName':'contoso'}

The critically important things to note are:

  • HTTP method: POST (GET will not work)
  • you specify the name of you method on the aspx page as SomePage.aspx/[MethodName]. In this case:

    SomePage.aspx/DoSomething

  • you pass the parameters of the method as JSON. This method has one string parameter: shiftName. This means i constructed the JSON:

    {'shiftName':'contoso'}
    
  • with the request's JSON content type, you have to specify the Content-Type request header:

    ContentType: application/json;charset=utf-8
    

Given that my example WebMethod simply takes the supplied text, appends hi there, and returns that string, the response from the web-server is:

HTTP/1.1 200 OK
Content-Type: application/json; charset=utf-8
Content-Length: 24
Connection: Close

{"d":"contoso hi there"}

Where the HTTP response body is also a JSON string, with a single property called d. I don't know where they got d from, but there it is.

That's how you call a WebMethod using http (e.g. assembly language, COM, C#, Java, Delphi).

The most common question is how do you call it from the client using jQuery.

$.ajax({
       type: "POST",
       url: 'Catalogo.aspx/checaItem',
       data: "{ id : 'teste' }",
       contentType: 'application/json; charset=utf-8',
       success: function (data) {
           alert(data);
       }
});

Note: Any code released into public domain. No attribution required.

like image 82
Ian Boyd Avatar answered Nov 10 '22 03:11

Ian Boyd


You need to make sure that you have the scripthandlerfactory defined in your web.config...more here http://msdn.microsoft.com/en-us/library/bb398998.aspx

like image 32
Jeremy Howard Avatar answered Nov 10 '22 04:11

Jeremy Howard