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:
- 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.
Page.GetPostBackEventReference(txt_sssn_dt);
- 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.
__doPostBack("txt_sssn_dt", "TextChanged");
- 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.
function DoPostBack()
{
__doPostBack("txt_sssn_dt", "TextChanged");
}
- I called this function on the
OnChange
event of the date picker control. And, I got the solution.
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.