Introduction
Lots of times, we need to call server side code using JavaScript (it means Ajax call) and without postback. There are lots of technologies that are available for that. Some people use Ajax.dll to perform this operation. But now, when Ajax.NET framework is available, there is no need to use a third party DLL for Ajax call.
Background
There is no need to use any third party DLL for Ajax Call. Simply add the reference of System.Web.Extensions
.
Using the Code
Set the EnablePageMethods="true" in Script Manager
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<script language="javascript" type="text/javascript">
<!--
function CallSum()
{
var txt1 = $get("txt1");
var txt2 = $get("txt2");
var txtresult = $get("txtSum");
PageMethods.Sum(txt1.value,txt2.value,OnCallSumComplete,OnCallSumError,txtresult);
}
function OnCallSumComplete(result,txtresult,methodName)
{
txtresult.value = result;
}
function OnCallSumError(error,userContext,methodName)
{
if(error !== null)
{
alert(error.get_message());
}
}
</script>
Server Side Code:
[System.Web.Services.WebMethod]
public static int Sum(int arg1, int arg2)
{
try
{
return arg1 + arg2;
}
catch(Exception ex)
{
throw ex;
}
}