Introduction
This is a tutorial on how to call a server-side ASP.NET method from a client-side JavaScript method.
If you are wondering when that could become useful, imagine the following scenario:
A Web Application having an implemented authentication system.
Users log in with their username and password.
At any point the user is able to log out by clicking on the respective “Log Out” button.
On the server-side, the log out action would trigger a cleaning up process of user’s temp data.
However, the user instead of clicking on the “Log Out” button, may simply close the browser window. Now since HTTP is a stateless protocol, the server-side cannot directly detect the user’s action. Therefore the client-side (browser) would have to notify the server that the user is closing the window.
A solution to this problem would be to call a JavaScript function when the client-side “onUnload” event is triggered. The JavaScript function would then be able to call the appropriate server-side method to clean up the data.
The exact required AJAX mechanism to accomplish that kind of communication is described on the “Hello World” project below.
Please note that for the purpose of this tutorial all methods are kept as simple as possible, so that you can easily modify them for your application.
1. Creating a new ASP.NET project
AJAX is required, thus a new “AJAX enabled ASP.NET Web Application” has to be created on Visual Studio 2005 or “ASP.NET Web Application” on 2008.
2. Modifying the server-side code
Every server-side method that is called from the client-side, must be declared as “static”, and also has to be decorated with the [System.Web.Services.WebMethod] tag.
Now let’s create a simple function that returns a string value.
[System.Web.Services.WebMethod] public static string Message() { return "Hello from the server-side World!"; }
3. Modifying the ScriptManager
The “EnablePageMethods” attribute has to be added on the ScriptManager tag.
<asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" />
4. Adding a simple HTML button
We are going to add a simple HTML button rather than a server-side ASP.NET button control. The “onClick” event is going to be associated with the JavaScript function “GetMessage”.
<input onclick="GetMessage()" type="submit" value="Get Message" />
5. Adding the JavaScript code
Let’s add the “GetMessage” JavaScript function, which is going to call our server-side “Message” method.
function GetMessage() { PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure); }
The “OnGetMessageSuccess” is the name of the JavaScript function that will be called if the request is successful. Whereas the “OnGetMessageFailure” will be called if an exception is thrown.
So let’s add these two functions:
function OnGetMessageSuccess(result, userContext, methodName) { alert(result); } function OnGetMessageFailure(error, userContext, methodName) { alert(error.get_message()); }
Please note that you can give to the functions any name you wish, as long as they match the PageMethods call parameters.
If there are no errors, the “OnGetMessageSuccess” will show a pop-up window with our server-side “Message” text. Else, the pop-up will have an exception message.
6. Running the Web Application
This is it, we are ready to run our Web Application. Everything seems to be working just fine on Internet Explorer (IE6 and IE7):
However if we run it on Firefox (currently the latest version is 3.0.4) the pop-up will display the following message:
The server method ‘Message’ failed.
7. Fixing the Firefox issue
We just need to modify the button’s onclick event a bit:
<input type="submit" value="Get Message" onclick="GetMessage();return false;" />
And this would do the trick:
8. Here is the complete source code for your reference
Default.aspx
(Had to replace double quotes (“) with single quote (‘) in order to post it correctly.)
<%@ Page Language='C#' AutoEventWireup='true' CodeBehind='Default.aspx.cs' Inherits='AJAXEnabledWebApplication2._Default' %> <!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>Page</title> <script type='text/javascript'> function GetMessage() { PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure); } function OnGetMessageSuccess(result, userContext, methodName) { alert(result); } function OnGetMessageFailure(error, userContext, methodName) { alert(error.get_message()); } </script> </head> <body> <form id='form1' runat='server'> <asp:ScriptManager ID='ScriptManager1' runat='server' EnablePageMethods='true' /> <div> <input type='submit' value='Get Message' onclick='GetMessage();return false;' /></div> </form> </body> </html>
Default.aspx.cs
using System; using System.Data; using System.Configuration; using System.Collections; using System.Web; using System.Web.Security; using System.Web.UI; using System.Web.UI.WebControls; using System.Web.UI.WebControls.WebParts; using System.Web.UI.HtmlControls; namespace AJAXEnabledWebApplication2 { public partial class _Default : System.Web.UI.Page { protected void Page_Load(object sender, EventArgs e) { } [System.Web.Services.WebMethod] public static string Message() { return "Hello from the server-side World!"; } } }
Comments are always welcome!
Nice post, but how to pass a parameter to the server side method?
Thank You!
@Wally: Thanks!
Add the parameter on the server-side, for example Message(string name).
And then on the JavaScript, add the same parameter on the PageMethods call, like PageMethods.Message(name, OnGetMessageSuccess, OnGetMessageFailure)
I’ve been working with an exposed Web Service for a while now… I did not know about that error catching trick. Very cool. Nice article. One thing I cannot find, however, is how to pass a parameter from client-side to client-side… is that possible? (How do I get OtherVariableToPass into the fncJavascriptHandleReturn as OtherVariableToReceive w/o making the WebService send it back?)
function fncJavascriptDoSomething()
{
var OtherVariableToPass = “test”;
WebService.WebMethod(“paramToWebMethod”,fncJavascriptHandleReturn);
}
fncJavascriptHandleReturn(WebMethodResults,OtherVariableToReceive)
{
alert(WebMethodResults);
}
KI
@schmakt: Thanks! I guess that you can have your OtherVariableToPass outside of the functions, so that they can both access it.
yah, that’s what I ended up doing.
*annoyed* that there wasn’t a more direct way.
Thanks for the response 🙂
Thanks, in this article is exactly what I am searched.
i also heard about ıcallback inerface and ICallbackEventHandler .
they are also doing the same job
wha are the differences?
Hi
This example is calling a static server side method. Is is possible to call a non-static method as static method is not able to access other variables and controls in the page. Cheers
Ah, thanks!
I was have a frustrating time figuring out that Firefox quirk.
Good Job.
Hi
it was a good article i agree
but can i return one object from server to client
if it is return means how to handle in client side
please reply me
Thanks
vijay
@vijay:
Thank you.
You could probably pass your object’s data in JSON format, and then process them with Javascript on the client-side.
Hello webmaster
I would like to share with you a link to your site
write me here preonrelt@mail.ru
waisten km kmlk km
Thanks You
i would like to share your site
contach me
[…] I did some research and found an article entitled “How to call a server-side method from client-side JavaScript“. […]
Great tutorial, thanks 🙂
Why is step 7 necessary ?? Why is Firefox handling the event differently than IE ???
thanks hendrik
[…] I have see this 3 topics:http://www.dotnetcurry.com/ShowArticle.aspx?ID=109https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja…http://weblogs.asp.net/muhanadyounis/archive/2008/12/30/scriptmanager-and-masterpage-pagemethods.aspxAnd just the 3 use MasterPages, I can´t find any article that explain to me an interaction betweeen client side, and server side using MASTERPAGES.My all web site use master page, and i really need to acess from client side using javascript to some functions in server side, the big problem is.. i use MASTERPAGES i read the 3 article and it looks nice.. but doesnt help very much: I have this in MASTER PAGE:<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="WebApplication1.Site1" %> <!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></title> <asp:ContentPlaceHolder ID="head" runat="server"> </asp:ContentPlaceHolder> </head> <body> <form id="form1" runat="server"> <asp:ScriptManager ID="ScriptManager1" runat="server" EnablePageMethods="true" EnableScriptGlobalization="true" LoadScriptsBeforeUI="true" EnableScriptLocalization="true"> <Scripts> <asp:ScriptReference Path="~/Javascript/MasterPageWSJS.js" /> </Scripts> <Services> <asp:ServiceReference Path="~/WebServices/MasterPageWS.asmx" /> </Services> </asp:ScriptManager> <div> <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server"> <asp:TextBox ID="TextBox1" onkeyup="CallService()" runat="server"></asp:TextBox> </asp:ContentPlaceHolder> </div> </form> </body> </html> And my asmx.cs is:using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Services; namespace WebApplication1 { /// <summary> /// Summary description for MasterPageWS /// </summary> [WebService(Namespace = "http://tempuri.org/")] [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)] [System.ComponentModel.ToolboxItem(false)] // To allow this Web Service to be called from script, using ASP.NET AJAX, uncomment the following line. // [System.Web.Script.Services.ScriptService] public class MasterPageWS : System.Web.Services.WebService { [WebMethod(EnableSession = true)] public static int CallFromMasterJS() { return 3; // todo: write the needed codes } } } And my javascript function is:function CallService() { //CallFromMasterJS() is the name of the service method alert("1"); var a = MasterPageWS.CallFromMasterJS(); alert("2");}When i run the web site, it fires the MessageBox with 1,But i can´t acess to MasterPageWS.CallFromMasterJS(); function Can anyone help me? I m desperateThanks Peter […]
Hi ,
i want to set my textbox values in ASPX from this webmethod .
so can i do ?
if any one know please tell me hom ?
regards,
Hitesh Panchal
Thanks a lot. That’s all I’m finding.
Тhanks, helped me a lot this tutorial
Hi,
Can you give me an example or solution, how to implement same solution with user control..
Thanks
Dharmesh
wonderful. thanks
hi
I want to call server side function from client side javascript function in timer. what i have to do for that thing.
thank u.
Your example not working
hi,
your code is working fine when i do not use master pages. but it is not working with them.
what will be solution for this.
thank u
Hi All,
Here is a nice article presenting parameterized web methods calling from clientside
http://aspdotnetcode.source-of-humor.com/articles/webmethods/Calling-ASPNet-Server-side-function-using-Javascript.aspx
cheers
When I try to use this code in my website I am getting the error as
Microsoft JScript runtime error: ‘PageMethods’ is undefined
what do i have to do to fix this?
and btw the method written on the server side is a static method, will this work for non static methods too?
and do i really need onMeassageSuccessful and onMessageFailure?
any help would be greatly appreciated.
Thanks
Hi, Bro make some change over her
Set EnablePageMethods =>True
Nice article, however some critical information seems to be missing. If you add this to a webpage with content, you can see a page refresh is occuring which defeats the whole ajax issue.
The button submitting needs to be in an update panel to stop the whole page updating.
I could be mistaken and missed something?
Hi,
Iam getting server method failed when calling a page method using js.
My page method retrieve more than 6500 data rows from Db. these rows are concatenated to a string and returned. When the number of is rows less than, means below 2500 it working fine. But if goes more it says server method failed .
each rows contain a string of length more than 30.
What i have to do in this case?
Great article. You saved my day. Many thanks 🙂
Thanks,
i got it…………
this is ultimate artical i was looking to add button in the gridview through which i can call server side function without postback or callback.
Thank You Very Much..
What if we want to access non-static members from this webmethod ?
Man, you saved my A$$ big time, can’t find enough thank you.
Thank very, very much…
Your code gives this error
Microsoft JScript runtime error: ‘PageMethods’ is undefined
i am from Viet Nam, so my English is so bad. 😀
but i want to say thank you for your post.
it’s very good.
man you are the best, thank you for the post. take care of your balls man =)
hi………………………
What if we want to access non-static members from this webmethod ?
What if we want to access non-static members from this webmethod ?
i cannot access my aspx control there How can i do it?
Nice.. Thanks..
If I would like to learn more in depth about server side, Can you recommend any website or books? I like a book that provide some sample codes.
Many Thanks. By the way, you did a great job.
If I’m working with MVC .. should I put both scripts in the same view?
Nice post… Saved my time a lot.
Thanks for sharing
Nice article.
thank you so much.
nice article. But how to use this on SSL pages.
Above code doesn’t work with SSL pages…
Hi
Thanks for your artcile. But I run these commands on visual studio 2010 there is “Microsoft JScript runtime error: Permission denied” error. How can i get rid of this error.
Hi All,
Here is a nice article presenting parameterized web methods calling from clientside
http://www.asp.net-crawler.com/articles/web-methods/calling-aspnet-server-side-function-using-javascript.aspx
cheers
[…] https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
Very good. Thank you.
Hay it’s really nice but i need some more information about JavaScript.
If user enter wrong username or wrong password then how to show
the alert(java script) in asp.net page.(No need to redirect any page)
Hello Sandeep,
You can easily use jQuery to update any html element depending on what the server-side method returns. For example $(“p#message”).html(“server-side message”);.
can we call a asp.net server side event handler from the client side in the same way with out postbacking.
This doesn’t work if you call the javascript method on form unload… It does goes to the codebehind method but never goes to the onGetMessageSucess javascript… any help..
Hello,
I am calling a webmethod from javascript in asp.net.When I use url rewriting the page method it is not working. for eg:
if i calll the page signup.aspx the web method is working fine but when i invoke the page signup using url mapping the web method is not working
[…] found a tutorial on calling a server-side method from javascript but is there a proper way to bind a jQuery object literal to data set dynamically in […]
[…] found a tutorial on calling a server-side method from javascript (it looks outdated to me) but is there a proper way to bind a jQuery object literal to data set […]
You have saved me a lot of time!!! thank you. Héctor Burgos from Chile
Hi,
Ive been looking for a way to integrate some server side validation with JQueryMobile, without exposing the log-in data via JavaScript. Your method above opens up the possibility for this to happen without waying the page down with .Net control and also without the need to revert to MVC.
Thanks.
[…] https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
[…] How to call server side method from Javascript […]
[…] you can use javascript to call pagemethods – https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
[…] https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
[…] How to call server side method from Javascript […]
[…] you can use javascript to call pagemethods – https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
[…] https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
[…] https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
[…] How to call server side method from Javascript […]
[…] you can use javascript to call pagemethods – https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
[…] https://decoding.wordpress.com/2008/11/14/aspnet-how-to-call-a-server-side-method-from-client-side-ja… […]
[…] ASP.NET – How to call a server-side slight from client-side JavaScript […]
Reblogged this on serenians.