Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / web / ASP.NET

Calling ASP.NET server-side events using JavaScript

3.12/5 (13 votes)
12 Apr 2008CPOL2 min read 1  
How to call ASP.NET server-side events using JavaScript.

Introduction

Very often, we want to execute ASP.NET server side events using JavaScript. Like, call a TextChanged event on the OnChange JavaScript event of a TextBox control. It can actually be done quite easily.

Background

In one of our ASP.NET Web Forms which is a part of our existing application, I was trying to implement and open an AJAX Modal Popup Extender dialog box on the click of an ImageButton control. But, there is a text box in the form in which a JavaScript attribute was bound for the OnPropertyChange event. The text box is actually a date picker control. If the user selects a date, then certain business logics get fired. But, just because of that, the modal popup control never worked with this form. Because, whenever the ImageButton was clicked to open the modal dialog box, the OnPropertyChange event was fired and the form.submit method was called which did not let the modal dialog box to open. So, the situation was that I had to avoid the form.submit method but keeping in mind that the business logic remained the same.

Using the code

To overcome this situation, I used the following code:

  1. I used the GetPostbackEventReference method of the Page object to register the ASP.NET server control which can create the postback using a client-side callback.
  2. C#
    Page.GetPostBackEventReference(txt_sssn_dt);
  3. Then, I used the __dPostBack event to fire the TextChanged event of the date picker control (txt_sssn_dt). This code had been placed inside the date picker JavaScript function, and it would be fired every time the user selects a date from the date picker.
  4. C#
    __doPostBack("txt_sssn_dt", "TextChanged");
  5. It was also necessary to write a simple JavaScript function to handle the situation when the user just wanted to type the date directly into the date picker (txt_sssn_dt). I wrote a JavaScript function called DoPostBack() for this.
  6. JavaScript
    function DoPostBack()
    {
       __doPostBack("txt_sssn_dt", "TextChanged");
    }
  7. I called this function on the OnChange event of the date picker control. And, I got the solution.
  8. JavaScript
    if(!IsPostback)
    {
        /...Implementation.../ 
         /.................../
        txt_sssn_dt.Attributes.Add("OnChange", 
              "javascript:return DoPostBack()")
    }

It's a very simple demonstration to show how to call a server-side ASP.NET event from the client-side. Please share your ideas if there is any other or better way to do this. I am available at sanjaysantra@hotmail.com.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)