- Writing Code to Statically Focus a Control
- Injecting a Startup Script Block
- Converting Static Code to Dynamic Code
- Summary
Injecting a Startup Script Block
Next, we can convert our static script into a dynamically injected startup script. This can be accomplished by adding a single method to the code-behind that injects the static code using the Page.RegisterStartupScript method, passing the script as text to that method. Listing 2 demonstrates the code-behind method.
Listing 2 Registering a Startup Script Block.
private void SetFocusControl() { const string script = "<script language=\"javascript\">" + " var control = document.getElementById(\"TextBoxAddress\");" + " if( control != null ) control.focus(); " + "</script>"; Page.RegisterStartupScript("Focus", Regex.Unescape(script)); }
The script block is converted to a valid C# string. Because we need to embed special characters such as quotation marks in the script (for example, "javascript"), we need to escape these characters within the string itself. To remove the escape characters, we then need to use the System.Text.RegularExpression.Unescape static method to remove the special escape characters (backslash). The result is the same script block in the HTML, but now we are injecting this block from the code-behind.