Create new account I forgot my password    

How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX
Rating: 125 user(s) have rated this article Average rating: 4.5
Posted by: Suprotim Agarwal, on 2/13/2008, in category "ASP.NET AJAX"
Views: this article has been read 172177 times
Abstract: You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions. In this article, we will be using PageMethods to call server-side functions using javascript.

How to call Server Side function from Client Side Code using PageMethods in ASP.NET AJAX
 
You cannot call server-side code ‘directly’ from client-side code. That is because by design, the server side code executes at server side and client side code at the client. However there are some workarounds. To call serverside code from javascript, you will need to use AJAX, and the easiest way out, is to use the ASP.NET AJAX Extensions.
One option while using Microsoft ASP.NET AJAX is to call ASP.NET Web services (.asmx files) from the browser by using client script. The script can call a webservice containing server-based methods (Web methods) and invoke these methods without a postback and without refreshing the whole page. However this approach could be overkill sometimes, to perform the simplest of tasks. Moreover the logic needs to be kept in a separate .asmx file. We need something that is more ‘integrated’ with our solution.
The option we are going to use in this article involves PageMethods. A PageMethod is basically a public static method that is exposed in the code-behind of an aspx page and is callable from the client script. PageMethods are annotated with the [WebMethod] attribute. The page methods are rendered as inline JavaScript.
Let us explore PageMethods with an example. The example we will be discussing here may not be the best example to explain PageMethods, but it will give you an idea of how to call server side code from client side. In this example, we will be connecting to the Customers table in the Northwind database. We will have some textboxes which will accept the CustomerID and in turn return the Contact Name of that Customer. The method returning ContactName will be called whenever the textbox loses focus. We will be using the onblur event where a javascript code will take in the value(CustomerID) from the textbox. This javascript function will then call a PageMethod (server side code) which returns the ContactName without any page refresh.
I assume that you have downloaded and installed ASP.NET AJAX extensions for ASP.NET 2.0. If not, I would advise you to download the extensions from here and install it before moving ahead. At any point of time, if you find a difficulty in understanding the code, download the sample project attached with this article at the end.
Step 1: Create an ASP.NET AJAX enabled website. Go to File > New > Website > ASP.NET AJAX-Enabled Web Site. Give the solution a name and location and click Ok.
Step 2: Drag and drop 2 labels and 4 textbox controls. We will be accepting the CustomerID from the user in the 2 textboxes and displaying the ‘ContactName’ in the other two textboxes. The textboxes that will display ‘ContactName’ has some properties set that will make it appear as a label without a border. Just set the BorderStyle=None, BorderColor=Transparent and ReadOnly=True. The markup will look similar to the following:
<form id="form1" runat="server">    
        <asp:ScriptManager ID="ScriptManager1" runat="server"/>
        <div>
        <asp:Label ID="lblCustId1" runat="server" Text="Customer ID 1"></asp:Label>
        <asp:TextBox ID="txtId1" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="txtContact1" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox><br />
        <br />
        <asp:Label ID="lblCustId2" runat="server" Text="Customer ID 2"></asp:Label>
        &nbsp;
        <asp:TextBox ID="txtId2" runat="server"></asp:TextBox><br />
            <asp:TextBox ID="txtContact2" runat="server" BorderColor="Transparent" BorderStyle="None"
                ReadOnly="True"></asp:TextBox>&nbsp;<br />
            </div>
    </form>
Before moving ahead, we will store our connection string information in the Web.config. Add the following tag below your </configSections> tag. Remember we have created an ‘ASP.NET AJAX enabled website’. The tag </configSections> along with some other tags automatically get added to the web.config.
<connectionStrings>
            <removename="all"/>
            <addname="NorthwindConnectionString"connectionString="Data Source=(local); Initial Catalog=Northwind; Integrated Security = SSPI;"/>
      </connectionStrings>
Step 3: Currently we will add a method, ‘GetContactName()’ which will accept a CustomerID and return the Contact Name information from the Northwind database, Customer table. We will then transform this method as a PageMethod.
C#
public static string GetContactName(string custid)
    {
        if (custid == null || custid.Length == 0)
            return String.Empty;
        SqlConnection conn = null;
        try
        {
            string connection = ConfigurationManager.ConnectionStrings["NorthwindConnectionString"].ConnectionString;
            conn = new SqlConnection(connection);
            string sql = "Select ContactName from Customers where CustomerId = @CustID";
            SqlCommand cmd = new SqlCommand(sql, conn);
            cmd.Parameters.AddWithValue("CustID", custid);
            conn.Open();
            string contNm = Convert.ToString(cmd.ExecuteScalar());
            return contNm;
        }
        catch (SqlException ex)
        {
            return "error";
        }
        finally
        {
            conn.Close();
        }
    }
VB.NET
 Public Shared Function GetContactName(ByVal custid As String) As String
        If custid Is Nothing OrElse custid.Length = 0 Then
            Return String.Empty
        End If
        Dim conn As SqlConnection = Nothing
        Try
            Dim connection As String = ConfigurationManager.ConnectionStrings("NorthwindConnectionString").ConnectionString
            conn = New SqlConnection(connection)
            Dim sql As String = "Select ContactName from Customers where CustomerId = @CustID"
            Dim cmd As SqlCommand = New SqlCommand(sql, conn)
            cmd.Parameters.AddWithValue("CustID", custid)
            conn.Open()
            Dim contNm As String = Convert.ToString(cmd.ExecuteScalar())
            Return contNm
        Catch ex As SqlException
            Return "error"
        Finally
            conn.Close()
        End Try
    End Function
Step 4: We will now transform this method as a PageMethod and then call this method GetContactName() from client side code; i.e. using JavaScript. To enable the method as a PageMethod, add the attribute [WebMethod] on top of the method:
C#
[System.Web.Services.WebMethod]
public static string GetContactName(string custid)
{
}
VB.NET
<System.Web.Services.WebMethod()> _
    Public Shared Function GetContactName(ByVal custid As String) As String
   End Function
At the sametime, add the attribute EnablePageMethods="true" to the ScriptManager as shown below:
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
Step 5: Let us now create the JavaScript that will call this server side code. Add a javascript file called script.js to your solution (Right Click Project > Add New Item > Jscript File > Rename file to script.js). Add the following code to the javascript file.
function CallMe(src,dest)
 {    
     var ctrl = document.getElementById(src);
     // call server side method
     PageMethods.GetContactName(ctrl.value, CallSuccess, CallFailed, dest);
 }
 
 // set the destination textbox value with the ContactName
 function CallSuccess(res, destCtrl)
 {    
     var dest = document.getElementById(destCtrl);
     dest.value = res;
 }
 
 // alert message on some failure
 function CallFailed(res, destCtrl)
 {
     alert(res.get_message());
 }
 
Step 6: We now need to reference this JavaScript file from our aspx page and invoke the ‘CallMe()’ method whenever the textbox loses focus. To do so:
Add a reference to the javascript file in the body tag as shown below:
<body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
    <form id="form1" runat="server">    
………
Step 7: To invoke the methods whenever the textbox looses focus, add these lines of code in the Page_Load() event
C#
if (!Page.IsPostBack)
        {
            txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");
            txtId2.Attributes.Add("onblur", "javascript:CallMe('" + txtId2.ClientID + "', '" + txtContact2.ClientID + "')");
        }
VB.NET
If (Not Page.IsPostBack) Then
                  txtId1.Attributes.Add("onblur", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")
                  txtId2.Attributes.Add("onblur", "javascript:CallMe('" & txtId2.ClientID & "', '" & txtContact2.ClientID & "')")
End If
As shown above, we are using the Attributes.Add that lets us add an attribute to the server control’s System.Web.UI.AttributeCollection object. The function ‘CallMe’ kept in the ‘script.js’ file will be invoked. We are passing the source and destination textboxes as parameters. The source textbox will contain the CustomerID. The CustomerID will be looked up in the Customers table and the corresponding ‘ContactName’ will be retrieved in the destination textbox.
Well that is all that is needed to invoke server side code from client side. Run the code. Type ‘ALFKI’ in the first textbox and hit the tab key. You will see that the javascript function goes ahead and calls the PageMethod GetContactName() using PageMethods.GetContactName. It passes the value of the source textbox which contains the CustomerID. The ‘ContactName’ returned is displayed in the second textbox below the first one, in our case the value displayed is ‘Maria Anders’.
Troubleshooting: ‘PageMethods Is 'Undefined'’ error
 
1.    Try setting EnablePageMethods="true" in the script manager tag
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true"/>
2.    Don't add the javascript references or code in the <head /> section. Add it to the <body> tag.
 
<body>
<script type="text/javascript" language="javascript" src="script.js"> </script>
    <form id="form1" runat="server"> 
    </form>
</body>
 
3.    Page methods needs to be static in code behind.
 
I hope you have got an idea of how to call server side code using JavaScript. I have used this technique successfully in a few projects and just love and admire PageMethods. I hope you found this article useful and I thank you for viewing it. The source code for this article can be downloaded from here.









Page copy protected against web site content infringement by Copyscape


How would you rate this article?

User Feedback
Comment posted by Vince Calaor on Wednesday, February 20, 2008 8:15 PM
Thanks for this it is really a great help
Comment posted by Satish Rathore on Thursday, February 21, 2008 5:11 AM
Wow my Problem is solved throuth ur code
i am so much Happy after run this code
again Thanks A lot..............
Comment posted by pradeep on Wednesday, February 27, 2008 6:13 AM
great article.
Comment posted by Iva Doycheva on Tuesday, March 04, 2008 9:01 AM
The error ‘PageMethods Is 'Undefined' ’ occurs when I try to use WebMethod and call it from javascript function in UserControl.

Can you help me how to resolve this problem.

Thanks, Iva
Comment posted by Suprotim Agarwal on Thursday, March 06, 2008 4:24 AM
Hi Iva,
Have you added the 'public' access modifier to Page Method?

http://forums.asp.net/t/1124197.aspx
Comment posted by Rupesh on Wednesday, March 12, 2008 2:19 PM
Its good to see the implementation
Comment posted by amit pundir on Thursday, March 13, 2008 4:21 AM
that is great article.
Comment posted by rakesh Kumar Sharma on Thursday, March 13, 2008 6:08 AM
i am using this code . its goods but my Question is what is the changes in web.config and how many webMethode create.
Comment posted by Maggie on Thursday, March 13, 2008 10:48 PM
Thx so much!! I finially make this work!!
Comment posted by vijay on Friday, March 14, 2008 7:42 AM
Im having my script mananger in master page. when am trying to call a method on servcer side, "PageMethod is undefined" error thrown.
In a single page it works fine.
Any idea regarding this issue.....
Comment posted by Suprotim Agarwal on Friday, March 14, 2008 9:08 AM
Vijay - Are you defining the PageMethod on the MasterPage? AFAIK, you cannot use PageMethods on a master page. However what you can do is define a base class with the web method and let all your pages inherit from that class.

That should work :)
Comment posted by Thomas Hansen on Tuesday, March 25, 2008 7:35 PM
Far easier method (and 100 times more flexible) using my employer's library is explained here; http://ajaxwidgets.com/Blogs/thomas/ajax_pagemethods_in_usercontro.bb
Comment posted by Suprotim Agarwal on Thursday, March 27, 2008 2:15 PM
Hi Thomas,
The post with your email has been removed. In the next build, i will try it and remove the email display feature as well. Thanks for your advice.
Comment posted by ghngjgjhgjhg on Tuesday, April 01, 2008 7:03 AM
jhjhjhjhj
Comment posted by ghngjgjhgjhg on Tuesday, April 01, 2008 7:05 AM
jhjhjhjhj
Comment posted by Ravi on Wednesday, April 16, 2008 6:27 AM
With your example, i got a solution for my work. But I am having a small doubt, from web method we can read the session data and we can call any public method in the class. please kindly give a response to this feedback.
Comment posted by Ravi on Wednesday, April 16, 2008 11:19 PM
With your example, i got a solution for my work. But I am having a small doubt, from web method we can read the session data and we can call any public method in the class. please kindly give a response to this feedback.
Comment posted by Nitin Anjana Pandya on Thursday, April 17, 2008 7:08 AM
Good Article
Comment posted by Suprotim Agarwal on Friday, April 18, 2008 12:36 PM
Hi Ravi..We can call a public method provided it is marked with the [WebMethod] attribute. What do you need the Session for?
Comment posted by Satheesh on Thursday, April 24, 2008 11:06 PM
Wonderful article! Thanks suprotim...
Regards,
Satheesh
www.codedigest.com
Comment posted by Anh Vo on Thursday, April 24, 2008 11:11 PM
Good Article
Comment posted by Satheesh on Thursday, April 24, 2008 11:43 PM
Wonderful article! Thanks suprotim...
Regards,
Satheesh
www.codedigest.com
Comment posted by venjoy on Friday, April 25, 2008 12:25 AM
Don't add the javascript references or code in the <head /> section. Add it to the <body> tag.
-----------------------------------
Why can't put javascript references or code in the <head /> section?
Comment posted by shailesh on Friday, April 25, 2008 2:11 AM
Very nice Article.

Its helpful to me on my project.

Regards
Shailesh
<a href="http://www.codegroups.com/blog/">Code Groups</a>
Comment posted by venjoy on Friday, April 25, 2008 6:34 AM
Don't add the javascript references or code in the <head /> section. Add it to the <body> tag.
-----------------------------------
Why can't put javascript references or code in the <head /> section?
Comment posted by Sundar on Friday, April 25, 2008 8:14 AM
How the values are passed to the parameters in these function CallSuccess,CallFailed.
And also the GetContactName function in server code accepts only one parameter, but in the javascript side u r passing additional parameters , how does this work can u explain me this.

Thanks in advance
Comment posted by Zeeshan Raees on Friday, April 25, 2008 8:47 AM
Very informative code and i liked it.
but i have a issue because i m new in javascript...
issue is,
when you called page method from javascript it has four arguments but in code behind file has a single argument
<b>Can any one EXPLAIN it for me</b>
Comment posted by Sundar on Friday, April 25, 2008 9:04 AM
How the values are passed to the parameters in these function CallSuccess,CallFailed.
And also the GetContactName function in server code accepts only one parameter, but in the javascript side u r passing additional parameters , how does this work can u explain me this.

Thanks in advance
Comment posted by Zeeshan Raees on Friday, April 25, 2008 9:14 AM
Very informative code and i liked it.
but i have a issue because i m new in javascript...
issue is,
when you called page method from javascript it has four arguments but in code behind file has a single argument
<b>Can any one EXPLAIN it for me</b>
Comment posted by James on Friday, April 25, 2008 9:30 AM
Might want to point out that webmethods don't work in user controls or server controls.  All the logic must be placed at the page level.  A serious drawback.
Comment posted by Suprotim Agarwal on Friday, April 25, 2008 10:45 AM
Sateesh, Shailesh, Anh Vo: Thanks

Venjoy: That's as the files get reloaded on each partial postback when kept in the <head>

Sundar, Zeeshan : That's the way the syntax works. The first 'set' of parameter in the PageMethods call is the parameter passed to the class method. Note that in our case, GetContactName takes only one parameter, that is custid. If the GetContactName took two parameters, the first 'set' of parameter would contain two parameters as shown below:

PageMethods.GetContactName(ctrl.value, secondparam, CallSuccess, CallFailed, dest);

The next 'optional' parameters are a callback for success and failure. The final parameter is the destination textbox where the value of the ContactName is displayed.
I hope it is clear now.

James: That's a very good point!! Check this link over here:
http://ajaxwidgets.com/Blogs/thomas/ajax_pagemethods_in_usercontro.bb
Comment posted by AShish on Friday, April 25, 2008 11:43 AM
Nice article man...............
Comment posted by czclk on Friday, April 25, 2008 12:26 PM
well, thanks for your toturial.
you said: "Don't add the javascript references or code in the <head /> section. Add it to the <body> tag."
but i put the javascript codes into the <head> sectioin, it runs well!
Comment posted by Suprotim Agarwal on Friday, April 25, 2008 9:34 PM
Hi czclk..I advised not to add the code into <head> if you get that error ' ‘PageMethods Is 'Undefined'’.
Comment posted by Anas on Sunday, April 27, 2008 2:52 AM
Thanks  very good article
Comment posted by Sundar on Monday, April 28, 2008 12:23 AM
Thanks a lot Suprotim Agarwal. Good Article looking forward more like this from u..

Once again Thnx for the reply and for this article.
Comment posted by Praveen on Wednesday, April 30, 2008 7:44 AM
Hi,
I am trying to call a function using PageMethods.
Just to start, the server side function just returns a string value and does nothing else.
But I always get the error saying that.
The server side method 'Test' failed.
I am displaying this message using Error.get_message
I am not able to get the actual error code or cause for the error.(tried stackTrace with noluck)

Can somoeone please help, this is urgent..

Thanks in advance.
Comment posted by Saran K on Friday, May 09, 2008 3:27 AM
I am manually loading a usercontrol in the webmethod(GetContactName--listed in the article) and the usercontrol holds ajaxtoolkit control while executing the page im getting the following error :          Error executing child request for handler 'System.Web.UI.Page'

Pls help me in solving this issue
Comment posted by Mahesh on Friday, May 09, 2008 6:44 AM
Very Very Nice article
Comment posted by pinky on Friday, May 23, 2008 2:55 AM
so nice that's the point i want
Comment posted by Ashok on Wednesday, July 09, 2008 10:57 AM
Wow!  Cool!  Good stuff!
Comment posted by Eralper on Wednesday, July 16, 2008 4:14 AM
Thanks for the sample application and download Suprotim.
Also I found the trouble shooting section on PageMethods is undefined error.
But the HEAD tip did not work for my case.

Eralper
http://www.kodyaz.com
Comment posted by Suprotim Agarwal on Wednesday, July 16, 2008 1:44 PM
Eralper: Does that mean that the code did not work as expected when you added it to the body section. What is the error that you get
Comment posted by Jeffrey on Monday, July 28, 2008 10:25 AM
The same article with different authors http://www.codeproject.com/KB/ajax/ajax_server_side_call.aspx, so who is the real and original author?
Comment posted by Suprotim Agarwal on Tuesday, July 29, 2008 7:24 AM
Hi Jeffrey,
Thanks for bringing that link to my notice. I checked the link and it seems the codeproject team has deleted it.

I think that answers the question
Comment posted by Jeffrey on Tuesday, July 29, 2008 10:08 AM
They are very efficient, because I also asked the same question there. If you google "hot to call server side function asp.net codeproject", you should be able to see the cached article there. It was posted on 19 May, 2008.
Comment posted by Jeffrey on Tuesday, July 29, 2008 10:38 AM
They are very efficient, because I also asked the same question there. If you google "hot to call server side function asp.net codeproject", you should be able to see the cached article there. It was posted on 19 May, 2008.
Comment posted by Suprotim Agarwal on Wednesday, July 30, 2008 10:28 PM
Unfortunately I believe the cache has also been deleted.
Comment posted by adil on Saturday, August 02, 2008 7:05 AM
great work. i am planning to copy this article and put it in my blog...
Comment posted by adil on Saturday, August 02, 2008 10:13 AM
great work. i am planning to copy this article and put it in my blog...
Comment posted by Suprotim Agarwal on Monday, August 04, 2008 10:53 AM
Hi Adil..I appreciate your comments, however all the articles are copyrighted and hence you should not copy them.
Comment posted by Martin on Wednesday, August 06, 2008 4:23 AM
Usage of this technique is very limited as we can not assign this as a datasource to the DataControls.I hope we can use this for getting single values to be displayed in for and display controls such as textbox ,label and etc..

am i correct ? please comment on this ..
Comment posted by a on Thursday, August 07, 2008 7:34 AM
e
Comment posted by Chris on Wednesday, August 13, 2008 5:38 PM
Great article! Thanks! I have one question (from a javascript newbie). How does the PageMethods.GetContactName() function call the CallSuccess() or CallFailed() functions? I see they are getting called since the textboxes are populated, but I don't get how they are called. Can you explain this or point me to a web page that explains it? Thanks in advance!
Comment posted by Suprotim Agarwal on Wednesday, August 13, 2008 8:46 PM
Chris: It's a callback feature. The first 'set' of parameter in the PageMethods call is the parameter passed to the class method. Note that in our case, GetContactName takes only one parameter, that is custid. If the GetContactName took two parameters, the first 'set' of parameter would contain two parameters as shown below:

PageMethods.GetContactName(ctrl.value, secondparam, CallSuccess, CallFailed, dest);

The next 'optional' parameters are a callback for success and failure. The final parameter is the destination textbox where the value of the ContactName is displayed.
Comment posted by Chris on Tuesday, August 19, 2008 1:54 PM
Thanks!!
Comment posted by Josh on Tuesday, August 19, 2008 6:03 PM
In all the other examples and documentation I have read, I do not see anything similar to your use of the dest variable.

Is that documented somewhere? That aspect of this does not work for me.

All the documentation I have found shows that there are additional parameters, several that point to additional handlers, like onTimeout or onAbort, and there are parameters for UserContext and MethodName, but I don't see any documentation that shows that we can pass a trailing parameter to represent the control to put the result into. Can you explain this further?

Thanks,
josh
Comment posted by Suprotim Agarwal on Wednesday, August 20, 2008 1:38 PM
Josh: If you debug the sample, the dest is being used in the CallSuccess and CallFailed() methods. In the CallMe() method, dest represents txtContact2.ClientID.
Comment posted by Sairam on Monday, September 08, 2008 9:14 AM
Thats a good one. But I want to access the UI elements of the page and session in the methods. Its not allowing because they are not static. How can I access the UI elements in the server method?
Comment posted by Nirav on Wednesday, September 10, 2008 12:31 AM
Hi Suprotim
I had been trying the same thing but still getting error "PageMethods is undefined".I am not using "ajaxenabled website",I am making simple web application.My function is written in default.aspx.cs and iwant ti to called from javascript.Please comment on this.
   [System.Web.Services.WebMethod]
        public GoogleObject GetGoogleObject()
        {
            GoogleObject objGoogle = (GoogleObject)System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT"];

            System.Web.HttpContext.Current.Session["GOOGLE_MAP_OBJECT_OLD"] = new GoogleObject(objGoogle);
            return objGoogle;
        }
Above is my function
PageMethods.GetGoogleObject(fGetGoogleObject);
this is .js code
Comment posted by mike river on Thursday, September 11, 2008 2:17 PM
Is it possible to invoke these PageMethod's from any other JS other then Script Manager ? How ?
Thanks.
Comment posted by Suprotim Agarwal on Thursday, September 11, 2008 9:58 PM
Sairam: PageMethods have to be static.

Nirav: PageMethods are an ASP.NET AJAX feature. You have to enable AJAX.

Mike: To be able to call static page methods as Web methods, you must set the EnablePageMethods attribute of the ScriptManager control to true. I do not know of any other method, except yes where you can call a 'parameterless' server side function using javascript(without asp.net ajax)

All of you should take a look at this doc: http://www.asp.net/ajax/documentation/live/tutorials/ExposingWebServicesToAJAXTutorial.aspx

Comment posted by NIrav on Friday, September 12, 2008 5:35 AM
Yes But  I had given the refernce of ajax,moreover I had edited my config file also.In past I had use ajax function in my app in similar manner.
Comment posted by Suprotim Agarwal on Saturday, September 13, 2008 6:06 AM
Nirav: Use the Contact page and mail me the code.
Comment posted by Manjula on Tuesday, September 23, 2008 6:06 AM
Very nice article..But in my application I am using  pagemethod technique and calling the chechurl() function which is my cs file but its not waiting for the function to get complete it,when i am displaying alert boxes its working fine.So please tell me how to stop the flow till that function gets executed completely?
Comment posted by logan on Thursday, September 25, 2008 9:17 AM
Is there any suggestion to handle a server side call for a client side event.senario is for an OnBlur event of texbox inside a datalist can a server call be made using ajax,and update a label in the corresponding row inside the same datalist.
Comment posted by Suprotim Agarwal on Friday, September 26, 2008 9:03 AM
logan: How about calling a webservice that gets the value for you. You can call this webservice from your client side code and then update the required label with the return value.
Comment posted by le van linh on Wednesday, October 29, 2008 3:27 AM
I try for aspx file which contains usercontrol it's not work,please help
Comment posted by gena on Monday, November 17, 2008 10:03 AM
To: le van linh
It will not work in such a way. I'll try to explain it in short and in general. Think it worth the individual article.
The thing is that when you add the WebMethod attribute to the static function, and allow the page methods on the ScriptManager, AJAX framework generates the
javascript object "PageMethods" with prototype of your function as it's method.
UserControl is another page, that ScriptManager cannot see. Try to experiment with the ScriptManagerProxy control, but think it will not help.
When I had the same problem, I solved it by creating "proxy" on the code behind.
Say, you have the UserControl Listing1 with static function GetContact(id).
You need to add on the default.aspx.cs the following "proxy":
[WebMethod]
public static string GetContact(string id)
{
  return Listing1.GetContact(id);
}

Regards,
Gennady
Comment posted by Penks on Tuesday, December 02, 2008 6:09 AM
hello, i try above code in user control and user control does not have body tag so where can I register this js. currently i have added this javascript code in user control . I have also try with the page where this control has been used. Still it generates error that pagemethods not found. Reply me as soon as possible. waiting for reply
Comment posted by Deepak on Friday, December 05, 2008 5:15 AM
Great sir
thanks a lot
Comment posted by kapil Chourasia on Friday, December 19, 2008 3:04 AM
i got error authentication failed when i m delete record using this page method
js code
function CallSuccessDel(orderId)
{
    PageMethods.deleteTradingRecord(orderId,CallSuccessDel1,CallFailedDel);
    return false;
    
}

function CallSuccessDel1(orderId,res)
{
    document.getElementById(orderId).style.display='none';
    document.getElementById("divIntraday").style.display="block";
    document.getElementById("divBlack").style.display='none';
    document.getElementById("divMsg").style.display='none';
}

function CallFailedDel(res)
{
    
   alert(res.get_message());
    
    document.getElementById("divIntraday").style.display="none";
    document.getElementById("divBlack").style.display='none';
    document.getElementById("divMsg").style.display='none';
    
}
c# code
DELETE_TRADING_RECORD_FOR_TRADINGGAME_PAGE is store procedure
[System.Web.Services.WebMethod]
    public static void deleteTradingRecord(string orderId)
    {
        object[] _val = new object[3];
        _val[0] = orderId;
        _val[1] = "";
        _val[2] = "";
        objGeneralFunction.connectionClose();
        try
        {
            objGeneralFunction.ExecuteProc("DELETE_TRADING_RECORD_FOR_TRADINGGAME_PAGE", _val, "temp");
        }
        catch (Exception ex)
        {
        }
    }
    #endregion
Comment posted by kapil on Friday, December 19, 2008 3:06 AM
plz help me
Comment posted by bux on Sunday, December 21, 2008 6:07 AM
hi, this is really good stuff. I would like to if it is possible to call server side methods(in aspx.cs) from the aspx page with out using AJAX.
Comment posted by jahangir Shahzad on Wednesday, January 14, 2009 5:17 AM
very good article! i am trying to use this code in a .ascx file and my script manager is on Masterpage and i m getting error pagmethod not defined i am defining it in.ascx.cs file.

any suggestions?
Comment posted by observer on Wednesday, January 28, 2009 3:40 AM
Hi kapil,

I think the 'authentication failed' error was thrown by the Database Server...

objGeneralFunction.ExecuteProc("DELETE_TRADING_RECORD_FOR_TRADINGGAME_PAGE", _val, "temp");

Just my thought.
Comment posted by jinal on Thursday, January 29, 2009 12:08 PM
very gud article
Comment posted by Todd on Friday, January 30, 2009 3:51 PM
Ok I'm getting the weirdest thing happening.  When I click a button to drive the javascript which is used to call my server side a login box pops up and asks me for my userid and password.  Wha?  Please help....
Comment posted by varsha on Friday, February 13, 2009 1:48 AM
abc
Comment posted by chethan on Tuesday, March 10, 2009 8:18 AM
nice one
Comment posted by pat on Monday, March 30, 2009 12:07 PM
this working fine, but i need to call server side function for a button click, example I am typing value in text box then click on a button to get result to a another textbox. so i have tried the above code but not work properly. i have add jscript on Button1.Attributes.Add("onclick", "javascript:CallMe('" & txtId1.ClientID & "', '" & txtContact1.ClientID & "')")
this is not work any help? please
Comment posted by Pradip Yadav on Tuesday, April 21, 2009 8:54 AM
Its Really good article.
Comment posted by Abhilash on Wednesday, May 06, 2009 7:41 AM
Really nice article.
I came across some core articles that can be related with this topic.
a) Why PageMethod is static? (http://encosia.com/2008/04/16/why-do-aspnet-ajax-page-methods-have-to-be-static/)
b) Why UpdatePanels are dangerous? (http://encosia.com/2007/07/11/why-aspnet-ajax-updatepanels-are-dangerous/)

Those who like this article, please take time to read this links also. since, it gives you some core ideas.

I bet.
Thanks & Take Care.
Comment posted by Nirman Doshi on Tuesday, May 12, 2009 5:31 AM
That's quite informative and really has saved my days.
I still have few queries.
1. All which Abhilash has posted
2. I tried to do all these things u mentioned here by putting it in a user control (.ascx) and it didn't work.
But when i tried to put the same thing in .aspx, it worked like a charm.
So what workaround is required to make this workable in user control just like its working in web form.
Comment posted by joseph jelasker on Saturday, May 16, 2009 6:23 AM
Nice article.The problem with me is that i want to call a server side funtion,used to load Drop Down ListBox,from Client side.so no argument would be passed.no result is got can u help me
Comment posted by Talal Shoaib on Tuesday, August 04, 2009 6:45 AM
Absolutely fabulous article...very informative...thanks man :D
Comment posted by Vaibhav Pitale on Monday, August 17, 2009 12:06 AM
Very Good Code Sir
I want a circular watch user control code in vb.net
Comment posted by Subramanian.R on Thursday, September 03, 2009 5:14 AM
Hi
This is really working good.
I have 1 question. can i call javascript method thro a button instead of textbox like


"txtId1.Attributes.Add("onblur", "javascript:CallMe('" + txtId1.ClientID + "', '" + txtContact1.ClientID + "')");"

instead can i use like this

"b1.Attributes.Add("onclick", "javascript:CallMe('" + txtId1.ClientID + "','" + txtContact1.ClientID + "')");"

it returns no error but it shows no value in txtcontact1
what shall i do........

feel free to reply me thro my mail id

thanks
Comment posted by ma on Friday, September 11, 2009 11:24 AM
Hi, i'm starting now with .net so...
I'm getting the undefined error, so where do I have to place my server-side code? in a base class you said, and then inherit that one from my aspx.vb, well I don't know, I can't, I can inherit just one and I need the System.Web.UI.Page.
Surely I'm missing a easy point as a beginner, can you help me?
Comment posted by Suprotim Agarwal on Wednesday, September 16, 2009 3:56 AM
ma: Sorry for the delay in my reply. Can you use the contact page to send your code and I will look into it.
Comment posted by mryildiz on Thursday, November 19, 2009 9:39 AM
thanks a lot!
it has solved my problem
Comment posted by Vlad on Wednesday, January 13, 2010 12:20 AM
hi, thanks for the code. Just some question, why page method generate a script on page source? this increase page size.
Comment posted by Vlad on Thursday, January 14, 2010 3:58 AM
hi, thanks for the code. Just some question, why page method generate a script on page source? this increase page size.
Comment posted by Gauri on Thursday, April 01, 2010 3:21 AM
i am getting error as
An error occurred loading a configuration file: Access to the path 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config' is denied.
Comment posted by Gauri on Thursday, April 01, 2010 3:22 AM
i am getting error as
An error occurred loading a configuration file: Access to the path 'C:\WINDOWS\Microsoft.NET\Framework\v2.0.50727\Config\machine.config' is denied.
Comment posted by Amar Nath Satrawala on Sunday, April 11, 2010 7:02 AM
Place static method in the content page in case of using master pages.
The method will be directly from scripts in user controls.
Comment posted by Jahangir Shahzad on Wednesday, April 14, 2010 5:52 AM
Great Article!!! Thumbs Up for u. I ve used that article on http://autospak.com to capture get the response from db when the use is entering its email for registration. if the email is already exist the use will get a message Already Used else Available
Comment posted by guy B. on Wednesday, April 21, 2010 2:52 AM
Great work!
Works perfectly.
Comment posted by Renato Lombardo on Wednesday, June 30, 2010 7:58 AM
What if I need to call a server-side method in a 3-layer architecture? For example, my Default.aspx contains a method LoadList(). This method instantiates a non-static business layer class and calls a non-static method GetList(). This cannot change. There is no way to convert Business and Data layers to static. When I try to do this, obviously get an error saying I am calling a non-static method from a static method.

Post your comment
Name:
E-mail: (Will not be displayed)
Comment:
Insert Cancel

NEWSLETTER