How to fire a Server Side Button click event from JavaScript?


There might be a simple solution for this, but I would like to dig into this more to give you more clarity.

Case 1: Through html ‘input’ type button, calling a server side button click event.

<form id=”form1″ runat=”server”>


      <input id=”btnClientSide” type=”button” value=”Caller”              onclick=”callServerSideClick()” />

      <asp:Button ID=”btnServerSide” runat=”server” Text=”BeingCalled” onclick=”btnServerSide _Click”/>

      <script language=”javascript”>

      function callServerSideClick()


      var cId=document.getElementById(“<%=btnServerSide.ClientID %>”);;






Whenever we click the btnClientSide’, we are calling the server-side click event of ‘btnServerSide’. No rocket science involved here to discuss more.

Case 2: Through Server side button, calling another server side button click event.

<form id=”form1″ runat=”server”>


        <asp:Button ID=”btnCaller” runat=”server” Text=”Button” OnClientClick=”callServerSideClick()” onclick=”btnCaller_Click”/>

      <asp:Button ID=”btnBeingCalled” runat=”server” Text=”BeingCalled” onclick=”btnBeingCalled_Click”/>

      <script language=”javascript”>

      function callServerSideClick()


      var cId=document.getElementById(“<%=btnBeingCalled.ClientID %>”);;






Whenever we click the ‘btnCaller’, we are calling the server side click event of ‘btnBeingCalled’. But here ‘btnBeingCalled’ server side event won’t get fired!!

Instead ‘btnCaller’ server side event will be fired (if any event is defined). What I mean

Here, is postback happens via ‘btnCaller’ but not because of ‘btnBeingCalled’.

For better understanding we go step by step debugging.

Whenever user clicks ‘btnCaller’ button, client side function call will be executed.

So in method call -‘callServerSideClick ()’, initially we get the client id for the button ‘btnBeingCalled’ and then in the next step, we registered the server side event call for that button.

But once the client side method is executed, this server side button ‘btnCaller’ demands for postback. So at this single point of time, form is asked to post for two different sever side events (methods).so JavaScript event registering is ignored and ‘btnCaller’ server side event will be fired.

Case 3: The above said problem will be solved if we could able to control the server side postback of caller button i.e. ‘btnCaller’. This can be done by returning false from the javascript function as….

<form id=”form1″ runat=”server”>


             <asp:Button ID=”btnCaller” runat=”server” Text=”Button” OnClientClick=”return callServerSideClick()” onclick=”btnCaller_Click” />

      <asp:Button ID=”btnBeingCalled” runat=”server” Text=”BeingCalled” onclick=”btnBeingCalled_Click”/>

      <script language=”javascript”>

      function callServerSideClick()


      var cId=document.getElementById(“<%=btnBeingCalled.ClientID %>”);;

      return false;






So here after registering the server side click event for ‘btnBeingCalled’, in the final step as we return false to the button which we clicked, this return is being assigned, it wouldn’t postback (disable the event till function returns true).

So here there is no ambiguity of server side event (which to fire), its that server side click event which got registered through JavaScript –‘btnBeingCalled_Click’ will get fired successfully.

Case 4: If in any case we want to fire both the server side events, when we click on the single button (‘btnCaller’), then we need to do it in code-behind.

<form id=”form1″ runat=”server”>


             <asp:Button ID=”btnCaller” runat=”server” Text=”Button” onclick=”btnCaller_Click” />

      <asp:Button ID=”btnBeingCalled” runat=”server” Text=”BeingCalled” onclick=”btnBeingCalled_Click”/>





protected void btnCaller_Click(object sender, EventArgs e)


               btnBeingCalled_Click(sender, e);


So whenever we click on the ‘btnCaller’, both the events i.e. btnCaller_Click and btnBeingCalled_Click are fired.



Microsoft Enterprise Library:


The Microsoft Enterprise Library is a collection of reusable software components (application blocks) designed to assist software developers with common enterprise development cross-cutting concerns (such as logging, validation, data access, exception handling, and many others). They are provided as source code, test cases, and documentation that can be used “as is,” extended, or modified by developers to use on complex, enterprise-level line-of-business development projects.


Ø       Application blocks are a type of guidance, the design of application blocks encapsulates the Microsoft recommended and proven practices for .NET application development. These good practices are demonstrated in the overall design of the Enterprise Library, as well in the context-specific guidelines in the design of individual application blocks.

Ø       Software developers can add application blocks to .NET applications quickly and easily. For example, the Data Access Application Block provides access to the most frequently used features of ADO.NET, exposing them through easily used classes. In some cases, application blocks also add related functionality not directly supported by the underlying class libraries.

Ø       They generally have strict security, reliability, and performance requirements.


  • Consistency. All Enterprise Library application blocks feature consistent design patterns and implementation approaches.
  • Extensibility. All application blocks include defined extensibility points that allow developers to customize the behavior of the application blocks by adding their own code.
  • Ease of use. Enterprise Library offers numerous usability improvements, including a graphical configuration tool, a simpler installation procedure, and clearer and more complete documentation and samples.
  • Integration. Enterprise Library application blocks are designed to work well together or individually.

Common Scenarios

Enterprise Library can be useful in a variety of situations:

  • Enterprise Library provides enough functionality to support many common scenarios that enterprise-level applications must address.
  • Enterprise Library can serve as the basis for a custom library. You can take advantage of the extensibility points incorporated in each application block and extend the application block by supplying new providers. You can also modify the source code for the existing application blocks to incorporate new functionality. You can also add new application blocks to Enterprise Library. You can either develop extensions for existing application blocks and new application blocks yourself, or you can use extensions and application blocks developed by others.
  • Enterprise Library is designed so that its application blocks can function independently of each other. You have to add only the application blocks that your application will use; you do not have to add the entire library.
  • Enterprise Library includes the source code and the unit tests for all application blocks. This means you can modify the application blocks to merge into your existing library or you can use parts of the Enterprise Library source code in other application blocks or applications that you build.
  • Enterprise Library includes documentation, Quick Start samples, and source code. You can use the library as a tool for learning architectural, design, and coding best practices.

Various Blocks:

  • Caching Application Block. Developers can use this application block to incorporate a cache in their applications. Pluggable cache providers are supported.
  • Cryptography Application Block. Developers can use this application block to incorporate hashing and symmetric encryption in their applications.
  • Data Access Application Block. Developers can use this application block to incorporate standard database functionality in their applications.
  • Exception Handling Application Block. Developers and policy makers can use this application block to create a consistent strategy for processing exceptions that occur throughout the architectural layers of enterprise applications.
  • Logging Application Block. Developers can use this application block to include standard logging functionality in their applications.
  • Policy Injection Application Block. Developers can use this application block to implement interception policies that can be used to streamline the implementation of common features, such as logging, caching, exception handling, and validation, across a system.
  • Security Application Block. Developers can use this application block to incorporate authorization and security caching functionality in their applications.
  • Unity Application Block. Developers can use this application block as a lightweight and extensible dependency injection container with support for constructor, property, and method call injection.
  • Validation Application Block. Developers can use this application block to create validation rules for business objects that can be used across different layers of their applications.

In my next posts, I’ll dig into details of each block.

Setting Value in Textbox with TextMode=”Password”

The data in the textbox with text mode set to ‘password’ is lost when postback occurs. And even we can’t set the text value the way that we normally would do by setting the Text Property. In .Net, Microsoft has locked the write-ability of textboxes by marking as password fields. It means, we cannot programmatically set the value of a password field. It’s some sort of a security measure.

In order to persist the value of a textbox upon postbacks, the following work around can be implemented ….

(Let’s assume the textbox as ‘TextBox1’)


TextBox1.Attributes.Add(“value”, TextBox1.Text);


Differences between ReadOnly & Enabled properties of an Asp:TextBox control :

ReadOnly : We Use the ReadOnly property to specify whether the contents of the TextBox control can be changed or not. Setting this property to true will prevent users from entering a value or changing the existing value. Note that the user of the TextBox

 control cannot change this property; only the developer can.

When its ReadOnly=true, its text is not preserved using the concept of “IPostBackDataHandler”. But if we want to preserve, we can do it explicitly as its content (if any) is still included with the form submission i.e. in Request Object.

To make this point clear, I’ll tell you the scenario depicting this.

I have TextBox with ReadOnly=true and through a javascript function i set its value when I click on html button. When I click on the html button, I could able to see the content changed in the textbox,  but when I posted my page using some other button control, I lost my value which I set in the textbox using client-side script ie. javascript. This is because no server-side processing of “IPostBackDataHandler” concept to preserve its content. So if we want, we can do this explicitly using..(Lets assume TextBox id is ‘t1’)

string s= Request.Form.Get(“t1”);

t1.Text = s;

Next Point to be discussed for ReadOnly=true case is “ViewState”.

TextBox content when changed using server side code, preserved in viewstate. Lets take the case, if we have TextBox(ReadOnly=true) and two buton controls named as ‘PostBack’ and ‘ChangeContent’.

On ChangeContent event if we changed the text(Initially nothing is there in the textbox) to “My Name is Khan” and then clicked the ‘ChangeContent’ button,we can see “My Name is Khan” in the textbox. But when we click on the ‘PostBack’ button(meant only to submit the form),changed text will be lost if disable the viewstate. In order to persist the server-side text changes, need to enable the viewstate.


Enabled : when we set Enabled=”false” for textbox control, it cannot be edited and its content is excluded when the form is submitted.

So no IPostBackDataHandler concept, no Request object to set explicitly as in the case of “ReadOnly”. Only viewstate concept is there to preserve the content that to content changed from server-side only.


Why does TextBox control retains its value across postbacks even though its ‘EnableViewState’ is set to ‘false’ :

I have an html textbox and an button server control in my form. I  have entered some value in textbox and posted the page to server using button click event. After postback, I lost my value in the textbox. The problem is ‘no state maintained’ for html controls. ie.. They will lose their values upon round trip to the server.

One nice thing about ASP.NET is that the Web controls in a Web Form remember their values across postback. It is a common misconception among developers that view state is somehow responsible for having TextBoxes, CheckBoxes, DropDownLists, and other Web controls remember their values across postback. This is not the case, as the values are identified via posted back form field values, and assigned in the LoadPostData() method during loadpostbackdata event (one of the event in page life cycle) for those controls that implement IPostBackDataHandler.

Load Postback Data Event :

The loadpostbackdata event only happens when the page has been posted back. A server control can indicate that it is interested in examining the posted back data by implementing the IPostBackDataHandler interface. In this stage in the page life cycle, the Page class enumerates the posted back form fields(data), and searches for the corresponding server control. If it finds the control, it checks to see if the control implements the IPostBackDataHandler interface. If it does, it hands off the appropriate postback data to the server control by calling the control’s LoadPostData() method. The server control would then update its state based on this postback data.

To help clarify things, let’s re-look at our example. That is, if you have a TextBox Web control on a page and the user enters some value into the TextBox and posts back the page, the TextBox’s Text property is automatically updated to the user’s entered value. This happens because the TextBox Web control implements the IPostBackDataHandler interface, and the Page class hands off the appropriate value to the TextBox class, which then updates its Text property.

To concretize things, imagine that we have an ASP.NET Web page with a TextBox whose ID property is set to txtName. When the page is first visited, the following HTML will be rendered for the TextBox: <input type=”text” id=”txtName” name=”txtName” />. When the user enters a value into this TextBox (such as, “Hello, World!”) and submits the form, the browser will make a request to the same ASP.NET Web page, passing the form field values back in the HTTP POST headers. These include the hidden form field values (such as __VIEWSTATE), along with the value from the txtName TextBox.

When the ASP.NET Web page is posted back in the load postback data stage, the Page class sees that one of the posted back form fields corresponds to the IPostBackDataHandler interface. There is such a control in the hierarchy, so the TextBox’s LoadPostData() method is invoked, passing in the value the user entered into the TextBox (“Hello, World!”). The TextBox’s LoadPostData() method simply assigns this passed in value to its Text property.

So now the issue is what is the use of view state for textbox control??

Only few properties for a control retain their state using this loadpostbackdata concept, because only those properties are implemented in this manner. But many properties are not implemented in such a fashion, Like.. if you consider that readonly property of textbox  is set to False by default. Then in the Page_Load if you are trying to change its readonly property to true based on certain condition. So after setting readonly property in Page_Load and if it is posted back by clicking the button. To retain its readonly property across postback, we need to enable viewstate for this property. Otherwise this property wont be retained across postback.

Similarly When we initialise an dropdown list server control statically using aspx page, like

<asp:DropDownList ID=”ddlCategories” runat=”server” EnableViewState=”false”>


            <asp:ListItem>Home Needs</asp:ListItem>

            <asp:ListItem>Baby Care</asp:ListItem>


And when we select an element from dropdown list and posted the page using button click event, this value is retained because “selectedindex” property of dropdown is persisted using LoadPostData(). But if we assign dropdown list manually like,

   protected void Page_Load(object sender, EventArgs e)


            if (!IsPostBack)


                ArrayList ar = new ArrayList();


                ar.Add(Home Needs);

                ar.Add(Baby Care);

                DropDownList1.DataSource = ar;




And disabled viewstate, on postback we cannot see the elements in the dropdown list because  view state is not enabled. So it will show empty dropdown on postback as datasource property is not implemented using LoadPostData().

Though selectedindex is persisted using LoadPostData(), but could not be shown as there are no elements in the list to show this saved selectedindex value. Hence when we enable view state value for dropdown list, binded values could be retained.

Similarly no need to enable viewstate to persist the ‘checked’ property for ‘CheckBox’, but need to enable the viewstate in order to persist properties like ‘Text’ etc.


How to get Yes/No buttons instead Ok/Cancel in Javascript confirm box with default focus set to No button ?

Javascript  Confirm dialog box is used to  prompt some message & retrieve some type of user interaction for further use on the webpage. In this process, Lets consider the following scenario.
Before deleting some file, if user need to be confirmed of doing it, confirm box throws a message like..
“Are you sure want to delete this file ? ” With ‘Ok & Cancel’ buttons to retrieve the user’s input.
Some confusion will arise with regard to ‘Cancel’ word. So it would be better if we have “Yes/No” instead of “Ok/Cancel”.
Also, default focus is set to ‘Ok’ button. This would allow ‘user keystroke’ problems.(Unnecessary deletion of the file if user(by mistake) clicks enter key). So it would be better if we have default focus set to “Cancel” (or “no”).
There might be many solutions to solve this problem, but the solution I implemented is
“VB Script- MsgBox” instead of confirm box.

<script type=”text/javascript”>
    var isChoice = 0;  
      function cancelClick()
      txt = “Are you sure want to delete this file ?”;
      caption = “”;// you can give any title
            // some code to delete the file
             return false;         
<script language=”vbscript”>
      Function vbMsg(isTxt,isCaption)
      testVal = MsgBox(isTxt,4+32+256 ,””)
      isChoice = testVal
      End Function

Some Points about VbScript MsgBox  :
The MsgBox function can return one of the following values:

  • 1 = vbOK – OK was clicked , 2 = vbCancel – Cancel was clicked , 3 = vbAbort – Abort was clicked , 4 = vbRetry – Retry was clicked , 5 = vbIgnore – Ignore was clicked , 6 = vbYes – Yes was clicked , 7 = vbNo – No was clicked

Note: The user can press F1 to view the Help topic when both the helpfile and the context parameter are specified.






Required. The message to show in the message box. Maximum length is 1024 characters. You can separate the lines using a carriage return character (Chr(13)), a linefeed character (Chr(10)), or carriage return–linefeed character combination (Chr(13) & Chr(10)) between each line


Optional. A value or a sum of values that specifies the number and type of buttons to display, the icon style to use, the identity of the default button, and the modality of the message box. Default value is 0
  • 0 = vbOKOnly – OK button only
  • 1 = vbOKCancel – OK and Cancel buttons
  • 2 = vbAbortRetryIgnore – Abort, Retry, and Ignore buttons
  • 3 = vbYesNoCancel – Yes, No, and Cancel buttons
  • 4 = vbYesNo – Yes and No buttons
  • 5 = vbRetryCancel – Retry and Cancel buttons
  • 16 = vbCritical – Critical Message icon
  • 32 = vbQuestion – Warning Query icon
  • 48 = vbExclamation – Warning Message icon
  • 64 = vbInformation – Information Message icon
  • 0 = vbDefaultButton1 – First button is default
  • 256 = vbDefaultButton2 – Second button is default
  • 512 = vbDefaultButton3 – Third button is default
  • 768 = vbDefaultButton4 – Fourth button is default
  • 0 = vbApplicationModal – Application modal (the current application will not work until the user responds to the message box)
  • 4096 = vbSystemModal – System modal (all applications wont work until the user responds to the message box)

We can divide the buttons values into four groups: The first group  (0–5) describes the buttons to be displayed in the message box, the second group (16, 32, 48, 64) describes the icon style, the third group (0, 256, 512, 768) indicates which button is the default; and the fourth group (0, 4096) determines the modality of the message box. When adding numbers to create a final value for the buttons parameter, use only one number from each group.


Optional. The title of the message box. Default is the application name


Optional. The name of a Help file to use. Must be used with the context parameter


Optional. The Help context number to the Help topic. Must be used with the helpfile parameter