Use JavaScript in Your Code Behind Files.
By Daniel N. Egan (DotNetDoc)
There are many new things that can be accomplished in ASP.Net that would take you quite a bit of coding if you were to try to accomplishthem in regular ASP. Among the advancements that ASP.net has brought to web programming is the use of code behind files. A Code behindfile helps us to separate our visual presentation layer from our business layer. If you programmed in ASP then you remember the spaghetticode that inevitably occurred when you added even the simplest functionality to your web pages. A code behind file gives you a wonderfulway of separating your code from your HTML tags. Even with its great power there are still times when you want action to happen on theclient-side of your web application (No trip to the server). For this you will want to use the tried and true web developer’s friend:JavaScript. You can still go into the HTML section and add JavaScript tags where you would like them to be; however, this still requiresdealing with spaghetti code, which makes things difficult to read and debug. A better solution in some situations is to add JavaScript toyour pages dynamically. That’s how the .Net framework classes do it. In this article I will show three scenarios in which you could useJavaScript to have client side functionality and I will show you how to do it in the code behind files.
Our first example is very simple. Here is the scenario:
When users click on a button or link on your aspx page, that is used to delete a record, you want to have a pop -up message ask them toverify if they are sure. In windows applications this is done with a MessageBox. But the messagebox class in not available to us in a webapplication. To accomplish this in an Asp.Net you will need to use a JavaScript confirm box. Instead of having to add an onClickattribute to your HTML tags, you can place them in your code behind file as shown below. To add a client side attribute to a button orlink on your form you can use the “Attrubutes.Add()” method of the control. It takes two parameters: the type of action, onClick,onBlur, etc..., and the JavaScript itself. This particular JavaScript will pop up a confirm box (Yes/No). The JavaScript functioncalled “Return” has two possible outcomes, true or false. The confirm box will return a true if “Yes” is pressed and false if “No” ispressed. If the users click on “No” then nothing happens. If they click on “Yes” then the application will proceed.
Our second scenario delves deeper into the process:
Most web sites have forms that users need to fill out. Some examples of this are comment forms and registration forms. When users reachthat page you want to make sure that the cursor in sitting in the correct textbox for them to start. This is a convenience for theusers. This eliminates the need to use their mouse to click in the textbox and also directs them to the place you want them to start.
The code below shows a sub procedure in a code behind file. It has a single parameter; “ctrl As System.Web.UI.Control”. All that isrequired to call this method is to pass the name of the textbox that you want to receive the focus. We begin by building the JavaScript.
This requires a little more code than our first example.
You will notice that the first thing I do is create a StringBuilder object. You could use a string to do this as well, but it is moreefficient using a StringBuilder. (StringBuilders will be covered in more detail in a later article). Suffice it to say that it is easyto use and is more efficient than concatenating strings. We start by creating the beginning script tag. The next line calls thedocument.getElementById function and concatenates it with the control that we are passing to the procedure. The third line is just theending script tag.
cmdDelete.Attributes.Add("onClick", "javascript:return confirm(' Sure You Wish To Delete?');")
You may have noticed that at the end of each line I have added a vbCrlf (Carriage Return Line Feed). This is so that when it writes outthe JavaScript to the page that is rendered it will put each part of the script on a separate line. This is not needed for scriptfunctionality but readability. With a short script like this it might not make much difference but as you create larger scripts you willwant to be able to read the script in case you need to debug it. Please remember, as opposed to Vb.Net, JavaScript is case -sensitive.Calling the method is simple. You just call SetFocus() in your Page_Load and pass it the name of textbox that you want to have thefocus. In the example below I have taken that just a bit farther. The aspx page loads the email that the user had entered into a cookie(code not shown). This is so that when users return to the page, they do not have to retype their email. When the page loads it checks to see if the cookie exists. If it exists, the password textbox receives the focus. If it does not exist then the email textbox receivesthe focus. This is to show you that you can set focus to a textbox dynamically in your code.
Dim
s.Append("<SCRIPT language=""javascript"">" & vbCrLf)
s.Append("document.getElementById('" + ctrl.ID + "').focus() " & vbCrLf)
s.Append("</SCRIPT>" & vbCrLf)
RegisterStartupScript("focus", s.ToString)
End Sub
‘No carriage return’s
<SCRIPT language="javascript">
‘With carriage return’s
document.getElementById('txtEmail').focus()
</SCRIPT>
You have a form where users submit information to you either by email or in a database. You want to be able to give them a confirmationbut you don’t want to send them to another page to do this. When they have submitted something successfully you would like to give thema message and then send them to the homepage. The sample below is overly simplified so that we can focus on the JavaScript itself. Ifthis was for a real application we would add more error checking. Please follow the comments in the code for a line by line detail ofwhat the code is doing.
Private Sub
'Put user code to initialize the page here
If Not
Try
If
email.Text = Request.Cookies("JGA_Email").Value
SetFocus(txtPassword)
Else
SetFocus(txtEmail)
End If
Catch
End Try
' Boolean variable will flag if an error was encountered
' Your code would go here.
' This will catch your exception and change the Boolean flag to false
bNoError =
Finally
' The Finally section of a Try Catch will run no matter what. Error or No Error
' First we need to create a StringBuilder object to hold our JavaScript
' If no error was encountered then ...
'Start creating our JavaScript by creating our opening tag.
sJSCode.Append(" <script language=""javascript"">" & vbCrLf)
' Here we are creating a variable to hold our message
sJSCode.Append(" var sMessage = 'Your Question has been submitted.';" & vbCrLf)
' In this line we are creating two JavaScript functionsan alert(OK Messagebox)
' that will show our message and a window location method that will send our user to
' the page we are looking to go. If you tried to add a
' Response.Redirect or a Server.Transfer here it would not work.
' Your alert script would never get processed
sJSCode.Append(" alert(sMessage);window.location = 'Home.aspx'" & vbCrLf)
' Here is our closing tag
sJSCode.Append(" </script>" & vbCrLf)
' We need to then register our code. This will make sure it runs when
' we do a postback
RegisterStartupScript("MyJSCode", sJSCode.ToString)
' This code does the same thing but tells the user there was an error.
sJSCode.Append(" var sMessage = 'An error was encountered';" & vbCrLf)
I hope that this gives you a jumping-off point to start learning how to use JavaScript in your code behind files. Client Side
functionality will greatly enhance any Asp.Net application that you create.
DotNetDoc