Click here to Skip to main content
15,887,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I want to call code behind function(c# function)from java script function please tell me how i can do it.
Posted

 
Share this answer
 
One way:

Add a hidden asp:Button to your aspx page (don't forget to add a click handler in your code behind), and from your javascript, just call the button's click method:

JavaScript
var button = document.getElementByID("buttonID");  
button.click(); 


Your click handler code can then call the desired c# method.
 
Share this answer
 
v2
Comments
mhamad zarif 8-Aug-11 12:16pm    
shouldn't he use buttonID.clientID ? since it has runat=server.
1. Try setting
C#
EnablePageMethods="true"
in the script manager tag
C#
<asp:scriptmanager id="ScriptManager1" runat="server" enablepagemethods="true" xmlns:asp="#unknown" />

2. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method
3. Page methods needs to be static in code behind
4. Javascript Calling:

JavaScript
// Your Code Behind method
PageMethods.Method1(CallSuccess, CallFailed);

//Success Method
function CallSuccess(res, destCtrl)
 {     
    Alert(res);
 }
 
 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }
 
Share this answer
 

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



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900