We can call methods from client side using AJAX extensions
- Static methods in an ASP.net page
- Methods of a ASP.net web service
The sample code for this article is at
Static methods in an ASP.net page
In this case the method resides in the Web page. In order to call we need to
- Set EnablePageMethods="true" in ScriptManager
- The method needs to be public and static
- Add [WebMethod] attribute to the method
[System.Web.Services.WebMethod]
public static string GetInformation()
{
return "Hello from Page Method";
}
From JavaScript we can now call the method as displayed below
<script language="javascript" type="text/javascript">
function GetInfoFromPage() {
PageMethods.GetInformation(OnSuccess, OnFail);
}
function OnSuccess(result) {
alert(result);
}
function OnFail(result) {
alert(result.get_message());
}
</script>
Methods in an ASP.net Web Service
In this case the method resides in the Web service. In order to call we need to
- Add [System.Web.Script.Services.ScriptService] attribute to the Web Service
- Add the service reference to the ScriptManager
[WebService(Namespace = "http://tempuri.org/")]
[WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
[System.Web.Script.Services.ScriptService]
public class DemoService : System.Web.Services.WebService {
public DemoService()
{
//Uncomment the following line if using designed components
//InitializeComponent();
}
[WebMethod]
public string GetInformation(){
return "Hello from Web Service method";
}
}
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
<Services>
<asp:ServiceReference Path="~/DemoService.asmx"/>
</Services>
</asp:ScriptManager>
From JavaScript we can now call the method as displayed below
<script language="javascript" type="text/javascript">
function GetInfoFromService() {
DemoService.GetInformation(OnSuccess, OnFail);
}
function OnSuccess(result) {
alert(result);
}
function OnFail(result) {
alert(result.get_message());
}
</script>