Asp.Net Call WebService With Parameters From JavaScript JQuery

This example covers how to Call Asp.Net WebService PageMethods Or WebMethod With Parameters From JQuery Or JavaScript.

To Call WebService PageMethod through Ajax ,JavaScript or JQuery we need to uncomment or add following line before writing WebMethod

[System.Web.Script.Services.ScriptService]

Add jquery-1.7.2.min.js in application and reference it in Head section of page.

<head runat="server">
<script src="jquery-1.7.2.min.js" type="text/javascript"/>  
</head>

Add and create Web Service by Right click on solution explorer > Add New Item > WebService.asmx.
I have created a WebMethod which takes and return string parameter in it.

Call Asp.Net WebService From JQuery Or JavaScript


C# CODE
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class WebService : System.Web.Services.WebService
{
    [WebMethod]
    public string Welcome(string name) 
    { 
        return "Welcome " + name;
    }
}

VB.NET CODE
 
 Public Function Welcome(name As String) As String
  Return "Welcome " & name
 End Function
End Class

Place one text input html control, one input button type on page, you can place asp.net button control either.
Enter Name: <input type="text" id="txtName" />
<asp:Button ID="btn" runat="server" Text="Invoke WebService" 
            OnClientClick="CallWebService(); return false;"/>
        
<asp:Label ID="lblMsg" runat="server" Text=""/>
 
<input type="button" id="btnCall" value="Call Service" 
       onclick="CallWebService(); return false;"/>

Add following Script in Head section of page to call PageMethod using JQuery.

To call WebService using JavaScript, we can write script as follows
Place ScriptManager on the page and add ServiceReference and path in it.

<asp:ScriptManager ID="ScriptManager1" runat="server">
<Services>
<asp:ServiceReference Path="~/WebService.asmx" />
</Services>
</asp:ScriptManager>

Write this Script in Head of page.

Build and run the code.

If you like this post than join us or share

Find More Articles