Monday, March 7, 2011

ASP.NET – How to call a server-side method from client-side JavaScript

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.
aspnet_server_side_from_client_side_1
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.
1[System.Web.Services.WebMethod]
2public static string Message()
3{
4    return "Hello from the server-side World!";
5}
3. Modifying the ScriptManager
The “EnablePageMethods” attribute has to be added on the ScriptManager tag.
1<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”.
1<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.
1function GetMessage() {
2    PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);
3}
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:
1function OnGetMessageSuccess(result, userContext, methodName) {
2    alert(result);
3}
4 
5function OnGetMessageFailure(error, userContext, methodName) {
6    alert(error.get_message());
7}
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):
aspnet_server_side_from_client_side_2
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.
aspnet_server_side_from_client_side_3
7. Fixing the Firefox issue
We just need to modify the button’s onclick event a bit:
1<input type="submit" value="Get Message" onclick="GetMessage();return false;" />
And this would do the trick:
aspnet_server_side_from_client_side_4
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.)
01<%@ Page Language='C#' AutoEventWireup='true' CodeBehind='Default.aspx.cs' Inherits='AJAXEnabledWebApplication2._Default' %>
02 
03<!DOCTYPE html PUBLIC '-//W3C//DTD XHTML 1.0 Transitional//EN' 'http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd'>
04 
05<html xmlns='http://www.w3.org/1999/xhtml' >
06<head runat='server'>
07    <title>Page</title>
08    <script type='text/javascript'>
09        function GetMessage() {
10            PageMethods.Message(OnGetMessageSuccess, OnGetMessageFailure);
11        }
12        function OnGetMessageSuccess(result, userContext, methodName) {
13            alert(result);
14        }
15        function OnGetMessageFailure(error, userContext, methodName) {
16            alert(error.get_message());
17        }
18    </script>
19</head>
20<body>
21    <form id='form1' runat='server'>
22    <asp:ScriptManager ID='ScriptManager1' runat='server' EnablePageMethods='true' />
23<div>
24            <input type='submit' value='Get Message' onclick='GetMessage();return false;' /></div>
25</form>
26</body>
27</html>
Default.aspx.cs
01using System;
02using System.Data;
03using System.Configuration;
04using System.Collections;
05using System.Web;
06using System.Web.Security;
07using System.Web.UI;
08using System.Web.UI.WebControls;
09using System.Web.UI.WebControls.WebParts;
10using System.Web.UI.HtmlControls;
11 
12namespace AJAXEnabledWebApplication2
13{
14    public partial class _Default : System.Web.UI.Page
15    {
16        protected void Page_Load(object sender, EventArgs e)
17        {
18 
19        }
20        [System.Web.Services.WebMethod]
21        public static string Message()
22        {
23            return "Hello from the server-side World!";
24        }
25    }
26}

No comments:

Post a Comment