Subscribe

RSS Feed (xml)

Adding Client-Side Script to a Web Form in ASP.NET

Use three methods to emit client-side script: the System.Web.UI.Page’s
RegisterStartupScript and RegisterClientScriptBlock methods, and the
System.Web.UI.WebControls.WebControl (Button) Attributes.Add method.
This simple login example asks the users to enter their names and passwords and then
click the Submit button.You first want to emit client-side JavaScript that will set the initial
browser focus to the username field.You also want to emit client-side script that will
require a confirmation from the users if the password field is blank.
The ASPX page is as follows:
<asp:TextBox id=”UserNameTextBox” runat=”server”></asp:TextBox>
<br>
<asp:TextBox id=”PasswordTextBox” runat=”server”
TextMode=”Password”></asp:TextBox>
<br>
<asp:Button id=”SubmitButton” runat=”server” Text=”Submit”></asp:Button>
In <script runat=”server” /> block or codebehind:
Public Sub Page_Load(sender As [Object], e As EventArgs)
‘ emit script to set initial focus
RegisterStartupScript(“focus”, _
“<SCRIPT language=’javascript’>” + _
“form1.UserNameTextBox.focus()” + _
“</” + “SCRIPT>”)
‘ emit script to check for blank password
RegisterClientScriptBlock(“myscripts”, _
“<SCRIPT language=’javascript’>” + _
“function checkPwd(){“ + _
“ if ( form1.PasswordTextBox.value == ‘’)” + _
“ if ( confirm(‘Are you sure about a blank password?’))” +
“ return true;” + _
“ else {“ + _
“ form1.PasswordTextBox.focus();” + _
“ return false;” + _
“ } else return true;” + _
“ } </” + “SCRIPT>”)

‘ add submit button onclick event to call checkPwd function
SubmitButton.Attributes.Add(“onclick”, “javascript:return checkPwd()”)
End Sub ‘Page_Load

The RegisterStartupScript method emits the client-side JavaScript that sets the initial
focus into the Web Form just before the closing tag of the Page object’s <form
runat=server> element, thus ensuring that the script will run when the page is first
loaded. The RegisterClientScriptBlock method emits the JavaScript containing the
checkPwd function just after the opening tag of the Page object’s <form runat=server>
element. Finally, you use the SubmitButton object’s Attributes.Add method to add the
button’s onclick event, which calls the JavaScript checkPwd function.

No comments:

Archives

Variety in the Web World