How trigger a JavaScript function from a server-side control in ASP.NET
I had a situation where I wanted an ASP.NET server-side control to launch a JavaScript function, as well as launching the VB.NET code in the code behind. I read a few articles on the web about it and the approach I used is based mainly on information from an article I found on Builder.com.
I prefer keeping JavaScript in a separate file so I can use it for multiple pages without rewriting it. If you need the code on one page, you will eventually need it on another. I used the following line of code in the <head> section of the aspx file to load the JavaScript:
<script language="JavaScript" type="text/javascript" src="script/somescript.js"></script>
This made any and all functions within the JavaScript file available to me.
The key to this method is to add an attribute to the control. You have to add the attribute after the code behind is compiled so I added it on the Page_Load event. The code looks something like this:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load
btnSubmit.Attributes.Add("onClick", "return someFunction();")
End SubYou could pass a parameter to the JavaScript function this way:
Private Sub Page_Load(ByVal sender As System.Object, ByVal e
As System.EventArgs) Handles MyBase.Load
btnSubmit.Attributes.Add("onClick", "return someFunction(parameter);")
End Sub


1 Comments:
It works, nice!
Post a Comment
Links to this post:
Create a Link
<< Home