ASP.NET includes an extremely rich object model that covers most of what developers
need for their development. The downside of the server side centric object model is
that once a page is rendered to HTML on the client, there is no way to run any
additional code until a server side postback is completed. Often this extra tip is not
something that is desirable.
Even though .NET doesn’t directly include any object references for directly creating
JavaScript. You do have the ability to insert JavaScript code into a string and then
register the code block on the page. Once the page is rendered the script block is
inserted into the HTML and can be triggered from the client side. Some of the most
common client side events are shown below.
OnFocus – Occurs when a control receives focus
OnBlur – Occurs when focus leaves a control
OnClick – Occurs when the user clicks on a control
OnChange – Occurs when the user changes value of certain controls
OnMouseOver – Occurs when the user moves the mouse pointer over a control
The code needed to insert script is added to the page load event of the web form.
For example, here is an example of adding a JavaScript alert to a page using the
OnMouseOver event.
Private Sub Page_Load(ByVal sender As System.Object, ByVal e As
System.EventArgs) Handles MyBase.Load
'Create the variable that included the script
Dim ClientScript As String = "<script language=JavaScript>
function ShowInfo() {alert('Pointer on the control'); }</script>"
' register the script on the page
If (Not IsClientScriptBlockRegistered("ShowInfo")) Then
RegisterClientScriptBlock("ShowInfo", ClientScript)
End If
TextBox1.Attributes.Add("onMouseOver", "ShowInfo()")
End Sub
When the page is rendered the HTML now contains the script block as shown below.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<HTML>
<HEAD>
<title>TestForm</title>
<meta name="GENERATOR" content="Microsoft Visual
Studio .NET 7.1">
<meta name="CODE_LANGUAGE" content="Visual Basic .NET
7.1">
<meta name="vs_defaultClientScript"
content="JavaScript">
<meta name="vs_targetSchema"
content="http://schemas.microsoft.com/intellisense/ie5">
</HEAD>
<body MS_POSITIONING="GridLayout">
<form name="Form1" method="post" action="TestForm.aspx"
id="Form1">
<script language=JavaScript> function ShowInfo() {alert
('Pointer on the control'); }</script>
<input name="TextBox1" type="text" id="TextBox1"
onMouseOver="ShowInfo()" style="Z-INDEX: 101; LEFT: 304px;
POSITION: absolute; TOP: 168px" />
</form>
</body>
</HTML>
9:32:16 PM
|