Friday, May 30, 2008

How to call Server Side Methods from Client Side Script in ASP .NET

Basically, you cannot call server side methods from client side script directly. Server side methods will execute at server side, client side script at client side, they live at two different worlds.

However, to call a server side method from client side, you can pass some information to the server as a request for an action, which can trigger a code behind method.

One simple solution to communicate with server from client side is to provide a hidden input field to store some flag or information and to read them on the server side.

To achieve this, put a hidden field in your HTML on the page, which use to store some flag. And in the code behind, you can call to the correct method that is needed according to the provided information.

<input id="hiddenVal" type="hidden" value="0" name="hiddenVal" runat="server"/>

Alternatively, you can put a hidden input button in your HTML on the page and then use script to call the button’s click method, as shown below:

<input type="button" id="btnHidden" style="DISPLAY:none" runat="server" onserverclick="server_side_handler"/>

Here is the sample of script to make the button clicks.

var btnHide = document.getElementById("btnHidden");;

Another way to call a server side method from client side script is by using ASP .NET AJAX Extensions. I assume that you already installed ASP .NET AJAX Extension, and then create a new ASP .NET AJAX-Enabled Web Site. The steps below will show you how this can be done.

Drag and drop a button into the page. The markup will look familiar to the following:

<form id="form1" runat="server">
    <asp:ScriptManager ID="ScriptManager1" runat="server"/>
        <asp:Button ID="btnGetMe" runat="server" Text="Button" />

Add the attribute EnablePageMethods="true" to the ScriptManager as shown below:

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

Note: This is very important or else you won’t be able to call the server side methods.

After that, add in a STATIC method to code behind of the page. This method then can be called from client side script easily. Mark the method as a WebMethod to expose the method, as below:

public static string HelloWorld(string value)
    return value;

Next step that you need to do is to call the page method. To call the method, you can specify a client-side method. The returned value from the server side will be passed as an argument to the client-side method.

<script type="text/javascript">
function CallMethod()
    PageMethods.HelloWorld("Hello, how are you today?", OnSucceeded);

function OnSucceeded(result)

To invoke the method whenever the button is clicked, add these few lines of code in the Page_Load() event.

if (!Page.IsPostBack)
    btnGetMe.Attributes.Add("onclick", "javascript:CallMyPageMethod()");

Try to run your website now.

Thursday, May 22, 2008


In Transact-SQL, you can use @@IDENTITY keyword to retrieve the value of the identity column whenever an INSERT, SELECT INTO or bulk copy statement is completed. It contains the last value that is generated by the statement.

For example, the query below inserts a new record into a table and returns a result set containing the ID of the inserted record.

INSERT INTO myTable (myName) VALUES (‘E-JULY’)

SELECT @@IDENTITY AS [@@IDENTITY] --Last inserted identity value will be inserted

However, beware of a potential for a subtle bug in some circumstances. For example, if you use @@IDENTITY and insert into a table (myTable) that run a trigger, and if the trigger inserts another record into another table (mySubTable), which happens to have an identity column, the @@IDENTITY will contain the identity value of table mySubTable instead of the identity value of myTable.

One option to prevent this from happening, we can use SCOPE_IDENTITY() function instead which will return the last inserted identity value in the current scope, in this case the returned value will be the identity value of myTable. Every trigger, function, procedure and batch has its own scope. SCOPE_IDENTITY shows the last inserted identity value in the current scope, which ignores any triggers that might fire.

INSERT INTO myTable (myName) VALUES (‘E-JULY’)

IDENT_CURRENT is limited to a specified table. It returns the last identity value generated for a specific table or view in any session and any scope.

INSERT INTO myTable (myName) VALUES (‘E-JULY’)

However, please note that SCOPE_IDENTITY and IDENT_CURRENT are only available in SQL Server 2000 or higher version.

Friday, May 16, 2008

Global.asax in ASP .NET

The Global.asax, which also known as ASP .NET application file, is located in the root directory of an ASP .NET application. This file contains codes that are executed in response to application-level and session-level events rose by ASP .NET or by HTTP modules.

There are a few things that needs to be take note about Global.asax, as below:
 The Global.asax is an optional file. You can remove the file if it is unnecessary.
 Any direct URL request to retrieve this file will be rejected automatically. External users are restricted from download or view the code written within it.
 If there are any changes on an active Global.asax file, the ASP .NET page framework will firstly complete all current requests for the application, sends the Application_End event to any listeners, and then restarts the application domain. In effect, this reboots the application, closing all browser sessions and flushing all state information. When the next incoming request from a browser arrives, the ASP.NET page framework re-parses and recompiles the Global.asax file and raises the Application_Start event.

In Visual Studio 2005, the Global.asax is not created by default. To create a Global.asax in your web project, right click your web site or web project in your solution explorer, choose Add New Item from the context menu. From the Visual Studio Installed Template, select Global Application Class and you can see something similar to the figure below:

Application and Session Events in Global.asax

Application Handlers:
Application_Start – invoked when the application first starts
Application_Init – invoked after Application_Start and is used for initializing code
Application_Disposed – invoked before destroying an instance of an application
Application_Error – invoked when an exception occurs
Application_End – invoked when the application ends and used to clean up variables and memory

Request Handlers:
Application_BeginRequest – invoked when an user makes a request for the application
Application_EndRequest – invoked at the end of each request
Application_PreRequestHandlerExecute – invoked before ASP .NET executes an event handler
Application_PostRequestHandlerExecute – invoked after ASP .NET handler has finished its execution
Application_PreSendRequestHeaders – invoked before ASP .NET sends HTTP header to the client
Application_PreSendRequestContent – invoked before ASP .NET sends contents to the client
Application_AuthenticateRequest – invoked before a user credentials are authenticated
Application_AuthorizeRequest – invoked on successful authentication of a user credentials. You can create your own user authorization to access the resources of an application
Application_ResolveRequestCache – invoked on successful completion of the authorization request
Application_AcquireRequestState – invoked when ASP .NET acquires the current state associated with the current request
Application_ReleaseRequestState – invoked before current state data in the session collection is serialized
Application_UpdateRequestCache – invoked before information is added to output cache of the page

Session Methods:
Session_Start – invoked when session starts on each user who requesting a page
Session_End – invoked when the session of a user times out or ends

Get paid for your opinions! Click on the banner above to join Planet Pulse. Its totally free to sign up, and you can earn UNLIMITED. Find out more by visiting PLANET PULSE.
July Code Blog Copyright © 2010 Blogger Template Designed by Bie Blogger Template