Web services are used to give websites program functionality via internet. Web services can accept messes and can return replies.

Example

A simple example to demonstrate, how to design and use that web services in our website.

Web service has “.asmx” extension.

To designing web service select New Project and in the New Project dialog box select “ASP.NET Web Service Application”

Now once the ASP.NET Web Service Application page opened we will do some coding part. 

Code (WebService1.asmx.cs)

 

//before writing any method in web service we have to write “[WebMethod]”
//within square brakets”[ ]”.
 
[WebMethod]
//creating method Add which will accept two arguments.
        public int Add(int a, int b)
        {
//returning value
            return a + b;
        }

 

Now, we need to compile the application and add the compiled application to IIS


in  order to get its web refrence, as we have to add its web refrence where we have


to use it.

 

Example to demonstrate how to use Web service in our website
Designing website

Web Site design code(Default.aspx)

 

<form id="form1" runat="server">
    <asp:TextBox ID="TextBox2" runat="server"
        style="z-index: 1; left: 397px; top: 112px; position: absolute; width: 194px"></asp:TextBox>
    <asp:TextBox ID="TextBox1" runat="server"
       
        style="z-index: 1; left: 396px; top: 78px; position: absolute; width: 194px"></asp:TextBox>
    <asp:Button ID="btnAdd" runat="server" onclick="btnAdd_Click"
        style="z-index: 1; left: 414px; top: 141px; position: absolute; height: 26px"
        Text="Add" />
    <asp:Label ID="Label2" runat="server" Text="TextBox2"
        style="position: absolute; top: 114px; left: 329px;"></asp:Label>
    <asp:Label ID="Label1" runat="server" Text="TextBox1"
        style="position: absolute; top: 79px; left: 329px;"></asp:Label>
    </form>
Code for adding two numbers in text boxes using the web service

Before writing the code we need to add the web reference of the web service. To add web reference of the web service right click in “Solution Explorer” and select “Add Web Reference”,   add web reference dialog box will appear. There add the web reference of the service in my case it is http://localhost:51481/Service1.asmx.

Code for website
 
//code for add button click
protected void btnAdd_Click(object sender, EventArgs e)
      {
//creating object of service created earlier.
        localhost.Service1 ws = new localhost.Service1();
//using Add method of web service and displaying the result in the page.
  Response.Write((ws.Add(int.Parse(TextBox1.Text), int.Parse(TextBox2.Text))).ToString());
      }
Screen shot of web page


  Modified On Nov-29-2017 10:05:59 PM

Leave Comment