Click here to Skip to main content
Click here to Skip to main content

Call Server Side Code by JavaScript using Ajax.NET Framework

By , 15 Jul 2007
 

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">
<!--
// Javascript function
function CallSum() 
{
//Get the controls
var txt1 = $get("txt1");
var txt2 = $get("txt2");
var txtresult = $get("txtSum");

//Call server side function
PageMethods.Sum(txt1.value,txt2.value,OnCallSumComplete,OnCallSumError,txtresult);

//Server side function gets the 2 arguments arg1 and arg2. 
//We are passing txt1.value and txt2.value
//for that. OnCallSumComplete is callback function for complete successfully. 
//OnCallSumError is callback
//function on error. txtresult is usercontext parameter.

//OnCallSumComplete,OnCallSumError,txtresult are optional parameters.

//If server side code executed successfully, then OnCallSumComplete will call.
//If server side code do not executed successfully, then OnCallSumError will call.
}

// Callback function on complete
// First argument is always "result" if server side code returns void 
// then this value will be null
// Second argument is usercontext control pass at the time of call
// Third argument is methodName (server side function name) 
// In this example the methodName will be "Sum"
function OnCallSumComplete(result,txtresult,methodName)
{
//Show the result in txtresult
txtresult.value = result;
}

// Callback function on error
// Callback function on complete
// First argument is always "error" if server side code throws any exception
// Second argument is usercontext control pass at the time of call
// Third argument is methodName (server side function name) 
// In this example the methodName will be "Sum"
function OnCallSumError(error,userContext,methodName)
{
if(error !== null) 
{
alert(error.get_message());
}
}
// -->
</script>
 
Server Side Code:
 
/// <summary>
/// Server side function Sum
/// </summary>
/// <param name="arg1">arg1</param>
/// <param name="arg2">arg2</param>
/// <returns>result(sum)</returns>
[System.Web.Services.WebMethod]
public static int Sum(int arg1, int arg2)
{
//On server side we can do anything, like we can access the Session.
//We can do database access operation. Without postback.
try
{
return arg1 + arg2;
}
catch(Exception ex)
{
throw ex;
}
}

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

About the Author

PareshDehadray1
Web Developer
India India
Member
No Biography provided

Sign Up to vote   Poor Excellent
Add a reason or comment to your vote: x
Votes of 3 or less require a comment

Comments and Discussions

 
You must Sign In to use this message board.
Search this forum  
    Spacing  Noise  Layout  Per page   
GeneralMy vote of 5memberAmol_Joshi10 Dec '11 - 18:25 
awesome
QuestionGetting a error ain the javascriptmemberdumpy31dec15 Nov '09 - 23:43 
Hi,
I have created my application as per the code given in the article. But when i try to run the application it is throwing a javascript run time error "Sys not defined". I have checked all the code but not able to find any such line in the aspx file please do help me as this is very urgent for me.
For you referance i am pasting the aspx and cs code.
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>
 
<%@ Register Assembly="System.Web.Extensions, Version=1.0.61025.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35"
Namespace="System.Web.UI" TagPrefix="asp" %>
 
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
 
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Untitled Page</title>
</head>
<body>
<script type="text/javascript" language="javascript">
function CallSum()
{
debugger
var val1=document.getElementById("txtval1").value;
var val2=document.getElementById("txtval2").value;
var lbresult=document.getElementById("lblresult").value;

PageMethods.Sum(val1.value,val2.value,OnCallSumComplete,OnCallSumError,lbresult);
}

function OnCallSumComplete(result,lbresult,Sum)
{
debugger
lbresult.value=result;
}

function OnCallSumError(error,userContext,Sum)
{
debugger
if(error !== null)
{
alert(error.get_message());
}
}
 
</script>
<form id="form1" runat="server">
<div>
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true">
</asp:ScriptManager>
<br />
<table>
<tr>
<td style="width: 100px">
Val 1</td>
<td style="width: 100px">
<asp:TextBox ID="txtval1" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Val 2</td>
<td style="width: 100px">
<asp:TextBox ID="txtval2" runat="server"></asp:TextBox></td>
</tr>
<tr>
<td style="width: 100px">
Result</td>
<td style="width: 100px">
<asp:Label ID="lblresult" runat="server"></asp:Label></td>
</tr>
<tr>
<td style="width: 100px; height: 26px">
</td>
<td style="width: 100px; height: 26px">
<input id="Button1" type="button" value="Calculate" /></td>
</tr>
</table>

</div>
</form>
</body>
</html>
 
Server Code:
 
[System.Web.Services.WebMethod]
public static int Sum(int arg1, int arg2)
{
//On server side we can do anything, like we can access the Session.
//We can do database access operation. Without postback.
try
{
return arg1 + arg2;
}
catch (Exception ex)
{
throw ex;
}
}
 
Prasenjit Basu_Chennai
GeneralPageMethods is undefinedmemberT.EDY6 Jul '09 - 17:33 
Hi,
 
First i wanna say it was great article.
But i when i try in my web page i got error said "PageMethods is undefined".
 
here's my code :
<script type="text/javascript" language="javascript">
function CountBack(myDiv)
{
   // my code here
       
   PageMethods.SignOut();
}
</script>
 
code behind :
[System.Web.Services.WebMethod]
public static void SignOut()
{
   FormsAuthentication.SignOut();
}
 

i already add ScriptManager with EnablePageMethods = "true" and call my javascript at body onload. Is there anything i must set to call the PageMethods property ?
 
Thank You
 
Regards,
 
Tomi

GeneralMy vote of 1memberBalamurugan R A6 Jan '09 - 19:21 
No detailed comments were available
Questionhow we can do this in asp.net 1.1memberkashish329 Apr '08 - 20:33 
i m using asp.net 1.1
how i can do this in asp.net 1.1
GeneralPlease Post The VB Codemembercijothomas29 Feb '08 - 20:35 
Can you please post the sam code in vb also.
i cannot fint the equivalentvb code of the following script
..how to make a webmethod in vb.net
 
[System.Web.Services.WebMethod]
public static int Sum(int arg1, int arg2)
{
 
}
GeneralRe: Please Post The VB CodememberBrooks Reese30 Mar '09 - 21:34 
<System.Web.Services.WebMethod()> _
Public Function GetString(ByVal value As String) As String
 
That should do the trick.
 
Br
QuestionWhy WEBMETHOD attribute tag ?membernitinjd@rediffmail.com27 Sep '07 - 20:08 
If i remove [System.Web.Services.WebMethod] , then application throws an error PageMethods Not found?
 
Can u pls provide reason for this.
AnswerRe: Why WEBMETHOD attribute tag ?memberPareshDehadray127 Sep '07 - 20:13 
We can run the PageMethods by javascript. To create a PageMethod we need to add [System.Web.Services.WebMethod] attribute at function level. By this this function treat as a PageMethod.
 
Thanks
Paresh
QuestionNot calling server side functionmemberimtiyaz_alamshah15 Jul '07 - 22:17 
In my case it is not calling server side function, do I need to set anything in web.config in order to call static webMethod.
 
Thanks in advance
AnswerRe: Not calling server side functionmemberPareshDehadray115 Jul '07 - 22:32 
1. Set EnablePageMethods="true" in ScriptManager object.
2. Server Side function should be public and static and add [System.Web.Services.WebMethod] attribute.
 
Try again. all the bestSmile | :)

GeneralRe: Not calling server side functionmemberimtiyaz_alamshah16 Jul '07 - 0:38 
I have already done both.
 
I have put break point on the server side function but it doesn't stop there and when I debug javascript I found that it calls OnCallSumError function which should be called on faliure of serverside function.
GeneralRe: Not calling server side functionmemberPareshDehadray117 Jul '07 - 4:51 
Please send me the code. I will check it.
GeneralRe: Not calling server side functionmemberxsoftdev16 Aug '07 - 12:53 
Did you find a solution to this, I am having the same problem. I get 'There was a problem processing the request.'
GeneralRe: Not calling server side functionmemberPareshDehadray119 Aug '07 - 20:51 
No, I am not getting this problem. So unable to find it's solution.
QuestionCalling non static methods.memberastrobolidos22 Jun '07 - 5:19 
Hi,
Congratulation for the great job. I have a question. It's possible call a non static method on the code behind file? I have trying but the code is only reached when you define a static method.
 
cheers.
 
Lisandro Pacheco
AnswerRe: Calling non static methods.memberPareshDehadray122 Jun '07 - 21:32 
Only static methods are allowed to make Web Method. Reason behind this is system can not access controls in this methods. You can access only session and the parameters which are passed in this method. So methods are only static. By this if you want to access any control then compile time error will come.
 
Thanks
Paresh Smile | :)
Questioncan we use this in usercontrol ?memberfrumiweb9 Jun '07 - 3:11 
can we use this in usercontrol ?
AnswerRe: can we use this in usercontrol ?memberPareshDehadray111 Jun '07 - 3:56 
yes we can use this in usercontrol, but that usercontol should be used at any web form.
GeneralCode snippet, not an articlemvpMark Nischalke28 May '07 - 4:26 
You should expand a little more, add more text than just code comments
 

only two letters away from being an asset

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Permalink | Advertise | Privacy | Mobile
Web02 | 2.6.130523.1 | Last Updated 16 Jul 2007
Article Copyright 2007 by PareshDehadray1
Everything else Copyright © CodeProject, 1999-2013
Terms of Use
Layout: fixed | fluid