[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More


.NET AJAX callbacks to ASPX Pages

Published on
12,770 Points
2 Endorsements
Last Modified:
ASP.NET AJAX callbacks to web service are becoming very popular and unavoidable these days. The feel that the user gets when only a part of the page is updated without even hindering the UI is the advantage that the callbacks offer. The wait for the full page to be posted back and results to appear is reduced thereby keeping a rich user experience. In some situations you would not want to expose the arguments and the methods it supports to the public through the ASMX file. This will require you to move the logic to specific ASPX files or inside the inherited base class. Specifically, this is the most important reason which, I feel, would require you to move web methods to ASPX pages.

Both ASP.NET AJAX Extensions and ASP.NET 3.5 support AJAX callbacks to the web methods placed in ASPX pages or the inherited base class. The following are the steps involved, and we will use a fictitious routine "GetEmployees" to exemplify what we are doing.

The first step is to expose GetEmployees as a web method.

1: public partial class Employees : System.Web.UI.Page
2: {
3: [WebMethod]
4: [ScriptMethod]
5: public static List<Employees> GetEmployees(string dept)
6: {
7:   // logic to get the Employee list
8: }

Open in new window

Important points to be noted :

1. The method needs to be decorated with [WebMethod]
2. The method needs to be decorated with [ScriptMethod] to enable callback
3. The method MUST be static

Go to ScriptManager tag and set the ScriptManager.EnablePageMethods property to true. This will make all the web methods on this page visible to the JavaScript client. Without enabling the EnablePageMethods property the webmethods will not be available in the client side. So always pay a keen attention to enable it.

1: <asp:ScriptManager ID=”ScriptManager1” runat=”server” EnablePageMethods=”true” />

Open in new window

Finally, Change the JavaScript code to call the method through the PageMethods object instead of the Web Service.The transport of data to the client side can be in XML, JSON, String etc. I would recommend using JSON because it is light weight, fast and can be implemented with ease. When I say transport of data it is actually the result from the GetEmployees() function which we have marked as the WebMethod. when using JSON also pay a little care to the eval() which is known to cause XSS issues.

1: function GetEmployees ()
2: {
3:     PageMethods. GetEmployees(dept ,OnSucceeded);
4: }
6: function OnSucceeded (result)
7: {
8:     // logic to display the result
9: }

Open in new window

 Happy coding :)

Expert Comment

when placing webmethod script in a webpage, this webpage has to host in iis in a separate virtual directory
OR just add new item (Web Service) within the project?
LVL 21

Author Comment

No need to add a new item to your project if you are going with pageMethods .. you can just add this in the code behind of the aspx file

Expert Comment

I get an error in my code below altough i took what you mentioned as a reference can u help me on where i made my mistake on?


you said

one thing that wont work in your code is System.Web.HttpContext.Current.Response.Write("CAME TO WEB METHOD?");

but i still get undefined error altough i took your reference as a guide so what should i do ?

    protected void Repeater1_ItemCommand(object source, RepeaterCommandEventArgs e)
        if (e.CommandName == "Delete")
            string hasta_adi = e.CommandArgument.ToString();
            // Write code to delete data from SQL
            // if this patient will be deleted what should be done is 
            bool i = checkpatientexists(hasta_adi);

            //if i is true that means operations exist with this patient ,warn the user again 
            //if user confirms again then proceed with deletion. !!!

         if (i == true)
          // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait operasyon(lar) bulunmaktadir gene de silmek istiyor musunuz?')==true){document.writeln('true');}else{document.writeln('false')}</SCRIPT>");
             Button btnDelete = e.Item.FindControl("btnDelete") as Button;

         // btnDelete.Attributes.Add("onclick", "return confirm('Hastaya ait operasyon(lar) bulunmaktadir gene de silmek istiyor musunuz?')");
         //  System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> confirm('Hastaya ait Operasyonlar bulunmaktadir...'+ btnDelete.CommandArgument.ToString()) </SCRIPT>");
         //  Response.Write("pressed OK");
          // System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> alert('Hit OK')</SCRIPT>");

          System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> if(confirm('Hastaya ait Operasyonlar bulunmaktadir ==>>" + btnDelete.CommandArgument.ToString() + "')==true){ PageMethods.M1(); };</SCRIPT>");
         //System.Web.HttpContext.Current.Response.Write("<SCRIPT LANGUAGE=JavaScript> confirm('" + btnDelete.CommandArgument.ToString() + "'adli hastaya ait operasyon(lar) bulunmaktadir...');</SCRIPT>");
    public static void  M1()
       // System.Web.HttpContext.Current.Response.Write("CAME TO WEB METHOD?");
        string s = "Fatih Dikili";

        //return Class1.M2();

Open in new window


Featured Post

Microsoft Azure 2017

Azure has a changed a lot since it was originally introduce by adding new services and features. Do you know everything you need to about Azure? This course will teach you about the Azure App Service, monitoring and application insights, DevOps, and Team Services.

Join & Write a Comment

Overview of OneDrive and collaboration.
Please check the video also in regards to recovery of deleted emails from office 365 admin center and through the MFCMAPI tool. I have mentioned each and every step with the proper steps that need to be taken care of.

Keep in touch with Experts Exchange

Tech news and trends delivered to your inbox every month