Search code examples
c#javascriptexceptionasmx

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.


Solution

  • 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