Use JavaScript in conjunction with ASP.net 2.0

Source: Internet
Author: User
Tags date central time zone end functions html form tostring web services visual studio
Asp.net|javascript


Adding JavaScript to a server control



Adding JavaScript to a particular server control in a asp.net page is very simple. Let's take a button server control for example. If you use any Microsoft Visual Studio 2005 to drag a Button HTML server control (HtmlInputButton Class) onto a page and run it as a server control, you should have the following code structure:



<input id= "Button1" type= "button" value= "button" runat= "Server"/>


This is a normal button that can be controlled programmatically by asp.net the page's code detach or server-side script. For example, to specify the button text when a page is generated, use the value of the button only after it becomes an HTML server control (right-click the control and then select Run As server control) property.



Visual Basic




Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
Button1.Value = DateTime.Now.ToString()
End Sub


C#




protected void Page_Load(object sender, EventArgs e)
{
Button1.Value = DateTime.Now.ToString();
}


This code only provides a button on the page, and the text of the button is the date and time.






Figure 1. Display the date and time on the button



A special note is that the ASP.net page here takes time from the server that generated the page. Therefore, if the WEB server is located at a location in the United States Central Time zone (CST-6 GMT), they will get the same time regardless of where the person requesting the page is located.



What if you want this button to show the time zone for the person viewing the page? The easiest way to accomplish this task is to use JavaScript on the client.



In this case, we want to place the computer time of the end-user (the viewer of the Web page) on a button Web server control. The following code shows how to accomplish this task:


Visual Basic

<%@ Page language= "VB"%><script runat= "Server" > 
Protected Sub button1_click (ByVal sender as Object, _< C1/>byval e as System.EventArgs) 
Response.Write ("Postback!") ") End    sub</script>



C# 

<%@ Page Language="C#" %>
<script runat="server">
Protected void Button1_Click(object sender, EventArgs e)
{
Response.Write("return!");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Use JavaScript</title>
</head>
<body οnlοad="javascript:document.forms[0]['Button1'].value=Date();">
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="button"
OnClick="Button1_Click" Font-Bold="True" Font-Names="Verdana"
Font-Size="Larger" />
</div>
</form>
</body>
</html>



In this small piece of code, notice how some of the button's properties are assigned to the server before being sent to the client browser. In this case, the font of the text on the button is changed to a bold Verdana of a certain size. When the client receives the HTML code for the button, the client JavaScript changes the text of the button to the current time on the end user's computer. The HTML code generated for the entire page is as follows:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
Using JavaScript
</title></head>
<body οnlοad="javascript:document.forms[0]['Button1'].value=Date();">
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
Value="/wEPDwUKMTY3NzE5MjIyMGRkVUxVdzEWBhD7U89t7JKIkQc6Cko=" />
</div>
<div>
<input type="submit" name="Button1" value="" id="Button1"
Style="font-family:Verdana;font-size:Larger;font-weight:bold;" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
Value="/wEWAgK394SHCAKM54rGBtsX8d2S8MO7sf02DOAiquFyBkeY" />
</div></form>
</body>
</html>

A postback will still appear when you click the button (viewed by the Response.Write command), and the new time will appear on the button control when the page is re-rendered. The result is shown in Figure 2.

 


Figure 2. Click the date button

 

In this case, we put some JavaScript directly into the <body> element of the page via the onload property. For the value of the onload property, we deliberately point to the HTML element named Button1 in the first <form> section (because there may be multiple forms in the HTML).

While using this method to add some JavaScript to work with ASP.NET Web server controls is easy, we can easily add a JavaScript command to the button itself, as shown in the following code example:

Visual Basic

<%@ Page Language="VB" %>
<script runat="server">
Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
Button1.Attributes.Add("onclick", _
"javascript:alert('More attention!!!')")
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Use JavaScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button id="Button1" runat="server" Font-Bold="True"
Font-Names="Verdana" Font-Size="Larger"
Text="Click me!"></asp:Button>
</div>
</form>
</body>
</html>

C#

<%@ Page Language="C#" %>
<script runat="server">
Protected void Page_Load(object sender, EventArgs e)
{
Button1.Attributes.Add("onclick",
"javascript:alert('More attention!!!')");
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Use JavaScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:Button id="Button1" runat="server" Font-Bold="True"
Font-Names="Verdana" Font-Size="Larger"
Text="Click me!"></asp:Button>
</div>
</form>
</body>
</html>

It is a good way to add additional JavaScript to a control-specific control using the server control's attribute attribute. In this case, JavaScript is added by using the Attribute.Add attribute with the script keyword and the script itself (both represented as string values).

Back to top back to top

Perform a simple button flip
When it comes to buttons on a Web page, the more common feature that Web developers want to give to buttons is the flip effect. The flip effect is that when the end user places their mouse over a button on the web page (without clicking the button), the button's color and shape will change. This feature is especially useful for web pages with multiple buttons, which is useful from a usage perspective and will notify the end user that they want to perform a click on the button before clicking the button.

This operation was easy to implement before the server control appeared, and now, despite the server control, it is not that difficult. The code to perform a similar operation is as follows:

Visual Basic
<%@ Page Language="VB" %>
<script runat="server">
Protected Sub ImageButton1_Click(ByVal sender As Object, _
ByVal e As System.Web.UI.ImageClickEventArgs)
Label1.Text = "Return!"
End Sub
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Use JavaScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:ImageButton id="ImageButton1"
Οnmοuseοver="this.src='button2.gif'"
Οnclick="ImageButton1_Click"
Οnmοuseοut="this.src='button1.gif'" runat="server"
ImageUrl="button1.gif"></asp:ImageButton>
</p>
<p>
<asp:Label id="Label1" runat="server" />
</p>
</div>
</form>
</body>
</html>


C#

<%@ Page Language="C#" %>
<script runat="server">
Protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Label1.Text = "Return!";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Use JavaScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:ImageButton id="ImageButton1"
Οnmοuseοver="this.src='button2.gif'"
Οnclick="ImageButton1_Click"
Οnmοuseοut="this.src='button1.gif'" runat="server"
ImageUrl="button1.gif"></asp:ImageButton>
</p>
<p>
<asp:Label id="Label1" runat="server" />
</p>
</div>
</form>
</body>
</html>

This time we don't assign JavaScript to the server control via the <body> element, but instead use the control's onmouseover and onmouseout events. For each event, we specify a JavaScript value. The onmouseover event indicates that the end user places their mouse over the control, while onmouseout indicates that the end user has moved their mouse over the control. In this case, we want to display an image when the mouse is over the button, and the original image when the page is loaded and when the mouse is removed from the button.

If you are using this type of control directly, instead of specifying the control in the form as we used JavaScript in the <body> element, you can use the this keyword followed by the property you are trying to change.

Back to top back to top

Set control focus
ASP.NET 2.0 now includes the ability to set (cursor) focus for one of the HTML form elements. Before ASP.NET 2.0, you had to use JavaScript yourself to do the same thing. For example, if you have multiple text boxes in your ASP.NET 1.x page, you can set the focus to the first TextBox control after loading by using the following code in the <body> tag of the page.

<body οnlοad="document.forms[0]['TextBox1'].focus();">
By using this constructor code, the element containing the ID TextBox1 will get the focus when the page is loaded, enabling the end user to start typing directly without having to use the mouse to position the focus.

ASP.NET 2.0 makes this task very simple by adding the Focus() method. Now you can complete the focus setting for the TextBox control with the following code:

Visual Basic

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
TextBox1.Focus()
End Sub

C#

Protected void Page_Load(object sender, EventArgs e)
{
TextBox1.Focus();
}

After the browser loads the page using this method, the cursor is placed inside the text box, waiting for you to start typing text. So you don't have to move your mouse to the appropriate location to start typing in the form. The Focus() method allows you to dynamically place the end user's cursor in a specified form element (not just a TextBox control, but any server control derived from the WebControl class).

Back to top back to top

Use larger JavaScript functions
Now that we can embed some JavaScript inside an HTML element, and even use JavaScript and Web server controls in a dynamic way, how do you put all the JavaScript functions in your code?

There are several ways to accomplish this task, we will introduce

Several more common methods that can be used in ASP.NET code. In this article, we'll show you how to use the new Page.ClientScript property. Before ASP.NET 2.0, you needed to use the RegisterStartupScript and RegisterClientScriptBlock methods. These two methods have now been eliminated. Two possible ways to register a script in ASP.NET 1.x require a set of keyword/script parameters. Since there are two separate methods involved, it is highly probable that some keyword name conflicts will occur. The Page.ClientScript property itself can do all script registrations, making your code less error-prone.

Back to top back to top

Page.ClientScript.RegisterStartupScript() method
One of the first options available was to register a script block with a .NET class that implements this functionality. The first is the RegisterStartupScript method. This class is best used when you have a JavaScript function that you want to start when the page loads. To give an example, create an ASP.NET page with two buttons in Visual Studio 2005. Button1 and Button2 are the IDs of the two buttons, respectively. Then, embed the following code inside the Page_Load event.

Visual Basic
Page.ClientScript.RegisterStartupScript(Me.GetType(), "MyScript", _
"function AlertHello() { alert('hello, ASP.NET'); }", True)
Button1.Attributes("onclick") = "AlertHello()"
Button2.Attributes("onclick") = "AlertHello()"

C#

Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript",
"function AlertHello() { alert('hello, ASP.NET'); }", true);
Button1.Attributes["onclick"] = "AlertHello()";
Button2.Attributes["onclick"] = "AlertHello()";

The two possible structures of the RegisterStartupScript method are as follows:


RegisterStartupScript (type, key, script)


RegisterStartupScript (type, key, script, script tag specification)

In the above example, you specified the type Me.GetType(), the keyword, and the included script, followed by a Boolean value of True (so that .NET automatically uses the <script> tag to embed the script in the ASP.NET page) .

Using this code in the Page_Load event will generate the following HTML code in the browser (some HTML code has been removed for the sake of brevity):

<html xmlns="http://www.w3.org/1999/xhtml" >
<head><title>
Using JavaScript
</title></head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
Value="/wEPDwUJMTM4ODA1MjE5D2QWAgIED2QWBAIBDw9kFgIeB29uY2xpY2s
FDEFsZXJ0SGVsbG8oKWQCAw8PZBYCHwAFDEFsZXJ0SGVsbG8oKWRk+DQIaJpw5
A7pyhzP8dxf/JGUSbA=" />
</div>
<div>
<input type="submit" name="Button1" value="Button"
Οnclick="AlertHello();" id="Button1" />
<input type="submit" name="Button2" value="Button"
Οnclick="AlertHello();" id="Button2" />
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
Value="/wEWAwK4yNWFBwKM54rGBgK7q7GGCHwBEr6DyGutQ/egvNrB3OYhCwM4" />
</div>
<script type="text/javascript">
<!--
Function AlertHello() { alert('hello, ASP.NET'); }// -->
</script>
</form>
</body>
</html>

When using this ASP.NET page, note that at the bottom of the page, at the end of the form (</form>), a JavaScript function is embedded.

It is important to specify a unique keyword for all JavaScript on the page (this can be done with the key parameter required in this method). If multiple JavaScripts have the same keyword name, only the first JavaScript will be embedded in the page.

Back to top back to top

Page.ClientScript.RegisterClientScriptBlock() method
Now let's create a better version of the button flip example by using the Page.ClientScript.RegisterClientScriptBlock method. The previous flip button example has a problem in that when the end user's mouse is placed on the button image, the flip image must be retrieved from the server by a separate request. A better flip button condition is that the flip image of the button has been downloaded and stored in the browser's cache so that when the end user places the mouse over the button, the flip image is immediately displayed. To do this, we have to build a JavaScript function. The following example shows the JavaScript function and how to use the RegisterClientScriptBlock method to place the function on the page. For this example, code separation requires only one Page_Load event and one button click event for the ImageButton server control.

Visual Basic

Protected Sub Page_Load(ByVal sender As Object, _
ByVal e As System.EventArgs)
Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), _
"MyScript", _
"if (document.images) {" & _
"MyButton = new Image;" & _
"MyButtonShaded = new Image;" & _
"MyButton.src = 'button1.gif;" & _
"MyButtonShaded.src = 'button2.gif;" & _
"}" & _
"else {" & _
"MyButton = '';" & _
"MyButtonShaded = '';" & _
"}", True)
ImageButton1.Attributes.Add("onmouseover", _
"this.src = MyButtonShaded.src;" & _
"window.status='Yes! Click here!';")
ImageButton1.Attributes.Add("onmouseout", _
"this.src = MyButton.src;" & _
"window.status='';")
End Sub
Protected Sub ImageButton1_Click(ByVal sender As Object, _
ByVal e As System.Web.UI.ImageClickEventArgs
Label1.Text = "Return!"
End Sub

C#

<%@ Page Language="C#" %>
<script runat="server">
Protected void Page_Load(object sender, EventArgs e)
{
Page.RegisterClientScriptBlock("MyScript", _
"if (document.images) {" +
"MyButton = new Image;" +
"MyButtonShaded = new Image;" +
"MyButton.src = 'button1.gif;" +
"MyButtonShaded.src = 'button2.gif;" +
"}" +
"else {" +
"MyButton = '';" +
"MyButtonShaded = '';" +
"}", true);
ImageButton1.Attributes.Add("onmouseover",
"this.src = MyButtonShaded.src;" +
"window.status='Yes! Click here!';");
ImageButton1.Attributes.Add("onmouseout",
"this.src = MyButton.src;" +
"window.status='';");
}
Protected void ImageButton1_Click(object sender, ImageClickEventArgs e)
{
Label1.Text = "Return!";
}
</script>
<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
<title>Use JavaScript</title>
</head>
<body>
<form id="form1" runat="server">
<div>
<p>
<asp:ImageButton id="ImageButton1"
Οnmοuseοver="this.src='button2.gif'"
Οnclick="ImageButton1_Click"
Οnmοuseοut="this.src='button1.gif'" runat="server"
ImageUrl="button1.gif"></asp:ImageButton>
</p>
<p>
<asp:Label id="Label1" runat="server" />
</p>
</div>
</form>
</body>
</html>

When using this code, the browser's HTML output would look like this:

<html xmlns="http://www.w3.org/1999/xhtml" >
<head id="Head1"><title>
Using JavaScript
</title></head>
<body>
<form name="form1" method="post" action="Default.aspx" id="form1">
<div>
<input type="hidden" name="__VIEWSTATE" id="__VIEWSTATE"
Value="/wEPDwUKMTcyMTcwOTQ2NA9kFgICBA9kFgICAQ8PZBYEHgtvbm1
vdXNlb3ZlcgVCdGhpcy5zcmMgPSB

NeUJ1dHRvblNoYWRlZC5zcmM7d2luZ
G93LnN0YXR1cz0nT2ggWWVzISBDbGljayBoZXJlISc7Hgpvbm1vdXNlb3V
0BSl0aGlzLnNyYyA9IE15QnV0dG9uLnNyYzt3aW5kb3cuc3RhdHVzPScnO
2QYAQUeX19Db250cm9sc1JlcXVpcmVQb3N0QmFja0tleV9fFgEFDEltYWd
lQnV0dG9uMXDJ4zl4FNylcdE+kep0e5wzi14T" />
</div>
<script type="text/javascript">
<!--
If (document.images)
{MyButton = new Image;MyButtonShaded = new Image;
MyButton.src = 'button1.gif'; MyButtonShaded.src = 'button2.gif';}
Else
{MyButton= '';MyButtonShaded = '';}// -->
</script>
<div>
<p>
<input type="image" name="ImageButton1" id="ImageButton1"
Οnmοuseοver="this.src = MyButtonShaded.src;window.status=
'Yes! Please click here! ';"
Οnmοuseοut="this.src = MyButton.src;window.status='';"
Src="button1.gif" style="border-width:0px;" />
</p>
<p>
<span id="Label1"></span>
</p>
</div>
<div>
<input type="hidden" name="__EVENTVALIDATION" id="__EVENTVALIDATION"
Value="/wEWAgLhoLy4DwLSwpnTCEKaKJJN3KmLU7TP4vwT5VSKMT+M" />
</div></form>
</body>
</html>









For this output, note that by using RegisterClientScriptBlock, the JavaScript function immediately follows the element <form> in the HTML code. In addition to adding JavaScript functions using the RegisterClientScriptBlock method, we've added some extra JavaScript (just to add some fun) so that when the end user places the mouse over the button, the text is displayed in the browser's status bar. As shown in Figure 3.

 


Figure 3. Active flip button

 

For all such JavaScript, the most gratifying thing is that normal postbacks for server-side events will work. Clicking ImageButton in this example will generate a postback that changes the text property of the tag server control.

The difference between Page.ClientScript.RegisterStartupScript and Page.ClientScript.RegisterClientScriptBlock

We've introduced you to two different ways to embed JavaScript functions into an ASP.NET page. So what's the difference between the two? The main difference is that the RegisterStartupScript method embeds JavaScript at the bottom of the ASP.NET page, just before the closing element </form> . The RegisterClientScriptBlock method is to embed JavaScript in the page immediately after the element <form> is turned on. So what is the difference? As we will see, this is very different.

As an example, here's how to place the focus on a text box on the page when the page is loaded into the browser - using Visual Basic that takes advantage of the RegisterStartupScript method:

Page.ClientScript.RegisterStartupScript(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
Since the text box on the page has been generated when the browser runs to the bottom of the page and executes this small piece of JavaScript, it has been placed on the page, so this method works fine. However, if you don't follow the above method, write the following code (using the RegisterClientScriptBlock method):

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "Testing", _
"document.forms[0]['TextBox1'].focus();", True)
The text box control will not get focus and will generate a JavaScript error on the page (as shown in Figure 4).

 


Figure 4. Error executing JavaScript

 

The reason for the error is that the browser will first encounter JavaScript and the text box will appear in the page. Therefore, JavaScript will not be able to find TextBox1.

Back to top back to top

Put JavaScript in a separate file (.js)
It is highly recommended to put the JavaScript function in a separate file (.js file). Once they are in a separate file and are part of a project, you can import the file into the page using some of the methods you've covered.

For example, the .js file can be included in an ASP.NET page with the following code:

Visual Basic

Page.ClientScript.RegisterClientScriptBlock(Me.GetType(), "MyScript", _
"MyJavaScriptFile.js")

C#

Page.ClientScript.RegisterClientScriptBlock(this.GetType(), "MyScript",
"MyJavaScriptFile.js");

Once you have imported the .js file into your ASP.NET page, you can call any JavaScript function as before. This is a good way to manage JavaScript functions and separate them from the logic of other ASP.NET pages. You can also easily use the same JavaScript functions in multiple ASP.NET pages using this method.

Back to top back to top

in conclusion
This article provides an overview of some common ways to use JavaScript in ASP.NET pages and some of the more common ways to use JavaScript. Some of the more important tips to note are to put the JavaScript in a separate .js file and embed the JavaScript into the page using the RegisterStartupScript and RegisterClientScriptBlock methods. It is also quite easy to deploy control-specific JavaScript to an ASP.NET page using the functionality of HtmlGenericControl.

About the author

Bill Evjen is an active advocate of .NET technology and the founder of community-based learning for .NET. Since the release of .NET in 2000, he has been actively working on .NET. In the same year, Bill created the St. Louis .NET User Group (http://www.stlnet.org), one of the world's first .NET user groups. Bill is also the founder of the International .NET Alliance (http://www.ineta.org), which has more than 400,000 members worldwide.

Based in St. Louis, Missouri, USA, Bill is the author and spokesperson for ASP.NET and XML Web services. He has authored or participated in more than 10 books, including Professional ASP.NET 2.0, Professional C# 2005, Professional VB 2005, XML Web Services for ASP.NET, and Web Services Enhancements: Understanding. The WSE for Enterprise Applications, Visual Basic .NET Bible, and ASP.NET Professional Secrets (both published by Wiley). In addition to writing books, Bill also participated in many conference presentations, including DevConnections, VSLive, and TechEd.



Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.