Wednesday, April 3, 2013

Call codebehind method from javascript in asp.net

Here i will show you how to call a codebehind method from javascript using Ajaxpro.

1. First go to http://ajaxpro.codeplex.com/releases/view/23363 website and download the Ajax.NET Professional Toolkit.

2. And also u should have Ajax control toolkit. To download go to this link http://ajaxcontroltoolkit.codeplex.com/ .

3. After downloading extract all the files, then go to your website--> Solution Explorer. Rightclick on your website in the solution explorer and goto add reference.
As given below in screenshots add reference of the AjaxPro.2.dll and AjaxControlToolkit.dll.







































4. Now goto your web.config file of the website and add <httphandlers> tag under the <system.web> tag

5. Then go to the codebehind page and add the required namespaces like shown below in the image and add this line on the page load event of the webpage.

AjaxPro.Utility.RegisterTypeForAjax(typeof(_Default));

 where _Default is the class name.
We will write [Ajaxmethod] above the method name which has to be called from javascript code.















6. Finally go to aspx page register the AjaxControlToolkit namespace in the page header.
  <%@ Register TagPrefix="Ajax" Namespace="AjaxControlToolkit" Assembly="AjaxControlToolkit" %>

Now call the javascript function and inside it call the codebehind method.
For example: i have taken a button and on button_click i will call the javascript function inside this i will call the codebehind method to return a string with some message which i will display it in the alert box.






















7. Now run the project and finally u can see the message from the code-behind getting pop'd up in the alert box. Cheers!!



No comments:

Post a Comment