Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you call a Javascript function from an ASPX control event?

How do you call a Javascript function from an ASPX control event?

Specifically, I want to call the function from the SelectedIndexChanged event of a DropDownList.

like image 463
Shaul Behr Avatar asked Dec 12 '25 20:12

Shaul Behr


1 Answers

I get a little nervous whenever I see this kind of question, because nine times out of ten it means the asker doesn't really understand what's going on.

When your SelectedIndexChanged event fires on the server, it fires as part of a full postback. That means that for that code to run, the entire rest of your page's load code also had to run.

More than that, the code runs as the result of a new http request from the browser. As far as the browser is concerned, an entirely new page is coming back in the result. The old page, and the old DOM, are discarded. So at the time your SelectedIndexChanged event code is running, the javascript function you want to call doesn't even exist in the browser.

So what to do instead? You have a few options:

  • Change the page so the control doesn't post back to the server at all. Detect the change entirely in javascript at the client. This is my preferred option because it avoids odd onload scripts in the browser page and it saves work for your server. The down side is that it makes your page dependent on javascript, but that's not really a big deal because if javascript is disabled this was doomed from the beginning.
  • Set your desired javascript to run onload in the SelectedIndexChanged event using the ClientScript.SetStartupScript().
  • Apply the expected results of your javascript to the server-model of the page. This has the advantage of working even when javascript is turned off (accessibility), but at the cost of doing much more work on the server, spending more time reasoning about the logical state of your page, and possibly needing to duplicate client-side and server-side logic. Also, this event depends on javascript anyway: if javascript is disabled it won't fire.
  • Some combination of the first and third options are also possible, such that it uses javascript locally if available, but posts back to the server if not. Personally I'd like to see better, more intuitive, support for that built into ASP.Net. But again: I'm talking about the general case. This specific event requires javascript to work at all.
like image 147
Joel Coehoorn Avatar answered Dec 15 '25 09:12

Joel Coehoorn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!