Monday, August 04, 2008

Create Javascript inside the code behind page

I often ran into the situation that need to create the Javascript function dynamically instead of having it on the Aspx page. For example, if there is a text box inside one of the view in the MultiView, the Javascript function to detect the Enter Key press will not work when the view with text box is not showing (the rendered html code does not contain this specific text box).

In case like this, we need to create the Javascript code dynamically. The Javascript function will only show up if the perticular view is showing. We use the "Page.ClientScript.RegisterClientScriptBlock" to accomplish this problem.

First, use ServerSideControl.FindControl("controlName").ClientId to find unique client side id for this control.

Then use the Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "ScriptId", "my Javascript code") to register the Javascript code.

To find this control inside the Javascript function: var btn = document.getElementById('" + strMyControlId + "');"

We can put above code inside a function and call it before making the view containing the text box visible to true.

MSDN: Page.ClientScript.RegisterClientScriptBlock
JavaScript with ASP.NET 2.0 Pages - part I

No comments: