Monday, April 16, 2012

Calling web services(ASMX) directly from javascript

Author : Prakash Pradeep Gopu
In this article am going to explain How to call the webservice with javascript using the Ajax extensions in .NET.
To do this the following steps you need to do 
Step1 : Developing the webservice :
Right-click on your web application, click Add/New Item and then Web Service. 
Call this web service  as "Demo". Add the following name space in the service 
 
using System.Web.Script.Services;
 
And copy and paste the following code in the demo.asmx.cs.


 [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    [System.ComponentModel.ToolboxItem(false)]
    [ScriptService]
    public class Demo : System.Web.Services.WebService
    {

        [WebMethod]
        public string HelloWorld(string ToSomeone)
        {
            return "Hello World " + ToSomeone;
        }
    }



You observe in the above code it consits of new attribute of service called[ScriptService] .Which is neede for to call our service with Script.

Step 2 : Devloping the Aspx page
Now create a new page say default.aspx page add the following code.

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script type="text/javascript">
        function CallService() {
            var name = document.getElementById('<%= txtName.ClientID %>').value;
        
            Webservicecall.Demo.HelloWorld(name, Callback);
        }

        function Callback(result) {
            var outDiv = document.getElementById("outputDiv");
            outDiv.innerText = result;
        }
</script>
</head>
<body>
    <form id="form1" runat="server">
    <ajax:ToolkitScriptManager ID="ScriptManager1" runat="server">
        <Services>
            <asp:ServiceReference Path="Demo.asmx" />
        </Services>
</ajax:ToolkitScriptManager>
<div>
<asp:TextBox ID="txtName" runat="server"></asp:TextBox>
    <asp:Button ID="Button1" runat="server" Text="Call Webservice"
        OnClientClick="CallService();return false;" />

</div>
    <div id="outputDiv">
   
    </div>
    </form>
</body>
</html>


If you observe there will be ajax script manager and in that script manager there will be Servicereference you need to give the path correctly i.e where you hoast your webservice.As Now it is in the same solution just I gave the name of the service.
Calling a webservice from javascript always needs two methods: one to make the actual call, and one to receive the results. The callback method is added as an extra parameter to the web service method parameters. In C#, the method has one parameter, so in javascript two.

Output :

 

No comments:

Post a Comment