Using JavaScript in ASP.NET pages can make your application seem to work faster and prevent unnecessary calls to the server. JavaScript can be used to perform client-side functionality in the user's browser without having to make calls back to the server; thus, saving resources.
The following example demonstrates how you can use an ASP.NET button to trigger a JavaScript call which modifies an ASP.NET TextBox.
Example
The following example will show you:
- how to dynamically add JavaScript to your page
- how to call the JavaScript function when the user clicks a button
- how to either allow or prevent the button from posting back to the server
First of all, you will have to create an ASP.NET project. This example uses a MasterPage, so when you create your ASP.NET project, be sure to add a MasterPage to it, then add a Web Content Form (aspx page) to your project and be sure to select your MasterPage while adding the Content Form.
In your ASPX page (your Content Form) you need to add a TextBox. This TextBox will be used to display the text "hello world".
You will also need to add an ASP.NET Button. This ASP.NET Button will trigger a JavaScript function that asks the user if they want to insert the text "hello world!" into the ASP.NET TextBox using JavaScript code...we'll get to the JavaScript function in a minute.
Keep in mind that once the ASP.NET button and TextBoxes are rendered for the browser, they are simple html objects that can be modified through JavaScript.
Your page should look something like the following:
Expand|Select|Wrap|Line Numbers
- <%@ Page Language="VB" MasterPageFile="~/MasterPage.master" AutoEventWireup="false" CodeFile="CTest.aspx.vb" Inherits="Test" title="Untitled Page" %>
- <asp:Content ID="Content1" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
- <asp:TextBox id="MyTextbox" runat="server"></asp:Textbox>
- <asp:Button id="HelloWorldButton" runat="server" text="Say Hi" />
- </asp:Content>
Please note that there are two click events for an ASP.NET button:
- The JavaScript onclick event, which is executed in the browser before the page is submitted to the server
- And the .NET OnClick event, which is executed on the server and handled by your VB.NET or C# code.
In order to call the JavaScript function we have to assign the button's JavaScript "onclick" event to call the method. There are two ways in which you can set the JavaScript "onclick" event: declaratively in your asp code using the OnClientClick property of the button; or dynamically using the button's "attributes" property in your VB.NET or C# code.
To declaratively provide a method to call during the JavaScript "onclick" event you would modify your button declaration and provide it with a value for the OnClientClick property:
Expand|Select|Wrap|Line Numbers
- <asp:Button id="HelloWorldButton" runat="server" text="Say Hi" OnClientClick="return DisplayHelloWorld();" />
Expand|Select|Wrap|Line Numbers
- <!-- The following will postback to the server and attempt to execute a method named DisplayHelloWorld -->
- <asp:Button id="HelloWorldButton" runat="server" text="Say Hi" OnClick="return DisplayHelloWorld();" />
The following code assigns the button's JavaScript "onclick" event to call a JavaScript method named "DisplayHelloWorld". It passes the method a parameter which is the ID that the TextBox has once it's rendered in the browser:
Expand|Select|Wrap|Line Numbers
- Private Sub Test_PreRender(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.PreRender
- CreateHelloWorldJavaScript()
- ' Please note that here we are providing the DisplayHelloWorld function with
- ' the MyTextBox.ClientID. The reason we use the ClientID is because when
- ' the TextBox is rendered in the browser it is given a special "ClientID" ...it's name
- ' changes from "MyTextBox" to something like "ctl00_ContentPlaceHolder1_MyTextBox"
- ' when using MasterPage. Therefore, in order for the JavaScript to know what the
- ' TextBox's id is in the page, we pass it the TextBox's ClientID
- If IsPostBack = False Then
- 'note the "return", if you set a button to return False it will not postback to the server.
- HelloWorldButton.Attributes.Add("onclick","return DisplayHelloWorld('" + MyTextbox.ClientID + "');")
- End If
- End Sub
This sub is responsible for dynamically creating the JavaScript and register it in the page:
Expand|Select|Wrap|Line Numbers
- Private Sub CreateHelloWorldJavaScript()
- If Not Page.ClientScript.IsStartupScritRegistered("HelloWorldScript") Then
- Dim script As New Text.StringBuilder
- script.Append("function DisplayHelloWorld(textboxID)" + vblf)
- script.Append("{" +vblf)
- script.Append(" if(confirm("Do you want to use JavaScript code to display the text?")==true)" + vblf)
- script.Append(" { document.getElementById(textboxID).value = 'Hello World! From JavaScript!';"+ vblf)
- script.Append(" return false;"+ vblf)
- script.Append(" }" +vblf)
- script.Append(" else"+ vblf)
- script.Append(" { return true;}"+ vblf)
- script.Append("}" +vblf)
- Page.ClientScript.RegisterStartupScript(page.GetType,"HelloWorldScript",script.ToString())
- End If
- End Sub
Now that the JavaScript is available in the browser, it can be executed when the button is clicked in the web browser because we have set the button to call it during the JavaScript "onclick" event.
The JavaScript function dynamically generated in the above code displays a confirm box which asks the user if they want to display the text using JavaScript code. If the user click "yes" then the JavaScript locates the TextBox, sets it's text to "Hello World! From JavaScript!", and returns false. If the user clicks "no" then the JavaScript function returns true which allows the page to post back to the server so that the server side code can be called.
It's important to note something that I skipped over quickly earlier.
In the PreRender event, when we are setting the JavaScript "onclick" event to call the JavaScript method, we are telling it return the value returned by the JavaScript "DisplayHelloWorld" method:
Expand|Select|Wrap|Line Numbers
- HelloWorldButton.Attributes.Add("onclick","return DisplayHelloWorld('" + MyTextbox.ClientID + "');")
Oh, there's one last thing to do: implement the server code that writes "Hello World" in the text box:
Expand|Select|Wrap|Line Numbers
- Protected Sub HelloWorldButton_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles HelloWorldButton.Click
- MyTextBox.Text = "Hello World! From the server!"
- End Sub
Recap
- You have a .NET button that will call a JavaScript function named "DisplayHelloWorld" to display the text "Hello World!" in a .NET TextBox.
The DisplayHelloWorld function takes one parameter: the ID of the .NET TextBox. The TextBox ID that is passed into the DisplayHelloWorld function is the TextBox's ClientID. The reason we use the ClientID is because (when using MasterPages or Web User Controls) the .NET TextBox is given a special ID when it is rendered in the browser that does not match the .NET variable name. - You have assigned the JavaScript call to the Button so that when the button's (JavaScript) "onclick" event is fired, it calls the JavaScript Function "DisplayHelloWorld".
- The "DisplayHelloWorld" JavaScript function has been registered in the page
- The JavaScript function asks the user if they want to display "Hello World" from the JavaScript code or from the Server Code. If the user wants to display the text from JavaScript, the function inserts the text "Hello World! From JavaScript" into the TextBox by retrieving the TextBox from the page using the document.getElementById() function. Otherwise, the function returns true, allowing the postback to occur.