[转] ASP.NET中使用javascript

1.使用Page.ClientScript.RegisterClientScriptBlock

使用 Page.ClientScript.RegisterClientScriptBlock可以防止javascript 函数放置在page的顶部

对于该输出,请注意:通过使用 RegisterClientScriptBlock,JavaScript 函数紧跟在 HTML 代码中开启元素 <form> 的后面。

下面就是个例子

前置文件4-10.aspx

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="4-10.aspx.cs" Inherits="_4_10" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>Untitled Page</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
<asp:Button ID="button1" runat="server" Text="click" OnClientClick="AlertHello()" />
    
</div>
    
</form>
</body>
</html>

后置文件4-10.aspx.cs

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _4_10 : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        String myScript 
= @"function AlertHello(){alert('hello World');}";
        Page.ClientScript.RegisterClientScriptBlock(
this.GetType(), "MyScript", myScript, true);
    }
}

 

运行一下看到什么??点击 "click"按钮得到了一个alert。不过你仔细检查我们代码看到什么?发现我们没有写<script type="text/javascript"></script> 这样的开始终止呢。原来Page.ClientScript.RegisterClientScriptBlock已经自动的帮我们生成了。当然这个是在你的function还算是比较大的情况下使用这。

 

上面一个是正确的例子,来分析一个异常的例子

 

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="4-10.aspx.cs" Inherits="_4_10" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml" >
<head runat="server">
    
<title>Untitled Page</title>
</head>
<body>
    
<form id="form1" runat="server">
    
<div>
    
<asp:TextBox ID="TextBox1" runat="server">Hello ASP.NET</asp:TextBox>
    
</div>
    
</form>
</body>
</html>

 

using System;
using System.Data;
using System.Configuration;
using System.Collections;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Web.UI.HtmlControls;

public partial class _4_10 : System.Web.UI.Page
{
    
protected void Page_Load(object sender, EventArgs e)
    {
        String myScript 
= @"alert(document.forms[0]['TextBox1'].value);";
        Page.ClientScript.RegisterClientScriptBlock(
this.GetType(), "MyScript", myScript, true);
    }
}

一运行发生了一个错误,根本不弹出窗口,原因就是当Page.ClientScriptRegisterClientScriptBlock已经生效的时候,textbox还没有开始生成呢。所以根本就无办法找到TextBox1

 这个时候只是需要修改一下Page.ClientScript.RegisterClientScriptBlock变成Page.ClientScript.RegisterStartupScript

2.Page.ClientScript.RegisterStartupScript()

当您有一个想要在页面加载时启动的 JavaScript 函数时.

 RegisterStartupScript 方法的两个可能结构如下: 
• RegisterStartupScript (type, key, script)
 
• RegisterStartupScript (type, key, script, script tag specification)
 
Page.ClientScript.RegisterStartupScript(this.GetType(), "MyScript",
   
"function AlertHello() { alert('你好,ASP.NET'); }"true);

Button1.Attributes[
"onclick"= "AlertHello()";
Button2.Attributes[
"onclick"= "AlertHello()";

3. Page.ClientScript.RegisterClientScriptInclude

这个是用来include js 文件的,以前我们都是写个<script type......>个头在html中,现在不需要了

直接在asp.net 页面中书写以下代码,比如我们有个myjs.js 文件

string myScript ="myjs.js";
page.ClientScript.RegisterClientScriptInclude(
"mykey",myScript);

声明一下,这第2篇不是自己写的,是来自MSDN http://www.microsoft.com/china/msdn/library/webservices/asp.net/JAVAwASP2.mspx?mfr=true

将 JavaScript 添加到服务器控件

将 JavaScript 添加到位于 ASP.NET 页面中的某个特定服务器控件是非常简单的。我们以按钮服务器控件为例。如果您使用任一 Microsoft Visual Studio 2005 将 Button HTML 服务器控件(HtmlInputButton 类)拖放到某个页面中,并将其作为服务器控件运行,则应具有以下代码结构:

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

这是一个普通按钮,可通过 ASP.NET 页面的代码分离或服务器端脚本以编程方式对其进行控制。例如,要在生成页面时指定按钮文本,只需在该元素变成 HTML 服务器控件(右键单击该控件,然后选择 Run As Server Control(作为服务器控件运行))后使用该按钮的 value 属性即可。

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();}

这段代码只是在页面上提供了一个按钮,该按钮的文本为日期和时间。


图 1. 在按钮上显示日期和时间

需要特别注意的是,此处的 ASP.NET 页面是从生成该页面的服务器来获取时间的。因此,如果 Web 服务器位于美国中央时区 (CST -6 GMT) 的某个位置,则无论请求此页面的人位于何处,他们都将获得相同的时间。

如果想要此按钮显示查看该页面的人所在时区的时间,又该如何呢?完成此项任务的最简单方法就是在客户端使用 JavaScript。

就此列举一例,我们要将终端用户(Web 页面的查看者)的计算机时间置于一个按钮 Web 服务器控件上。以下代码显示了如何完成该任务:

Visual Basic

<%@ Page Language="VB" %><script runat="server">    Protected Sub Button1_Click(ByVal sender As Object, _      ByVal e As System.EventArgs)        Response.Write("回发!")    End Sub</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>使用 JavaScript</title></head><body onload="javascript:document.forms[0]['Button1'].value=Date();">    <form id="form1" runat="server">    <div>        <asp:Button ID="Button1" runat="server" Text="按钮"          OnClick="Button1_Click" Font-Bold="True" Font-Names="Verdana"          Font-Size="Larger" />    </div>    </form></body></html>

C#

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

在此小段代码中,要注意按钮的一些属性在被发送到客户端浏览器之前是如何指定给服务器端的。本例中,按钮上文本的字体被更改为具有特定大小的粗体 Verdana。客户端接收到按钮的 HTML 代码后,客户端 JavaScript 即会将该按钮的文本更改为终端用户计算机上的当前时间。针对整个页面生成的 HTML 代码如下:

<html xmlns="http://www.w3.org/1999/xhtml" ><head><title>   使用 JavaScript</title></head><body onload="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>

单击该按钮仍会出现一个回发(通过 Response.Write 命令查看),当重新呈现此页面时,按钮控件上会显示新时间。结果如图 2 所示。


图 2. 单击日期按钮

在本例中,我们通过 onload 属性将一些 JavaScript 直接置于页面的 <body> 元素中。对于 onload 属性的值,我们特意指向了第一个 <form> 节(因为在 HTML 中可能会有多个 form)中名为 Button1 的 HTML 元素。

虽然使用此方法来添加一些 JavaScript 以便与 ASP.NET Web 服务器控件配合使用很简单,但是我们也可以很容易地将一个 JavaScript 命令添加到按钮本身,如以下部分代码示例所示:

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('多加注意!!!')")    End Sub</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>使用 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="单击我!"></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('多加注意!!!')");    }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>使用 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="单击我!"></asp:Button>    </div>    </form></body></html>

使用服务器控件的 attribute 属性将附加的 JavaScript 添加到控件特定的控件是一种很好的方式。本例中,通过将 Attribute.Add 属性与脚本关键字和脚本本身(两者均表示为字符串值)配合使用添加了 JavaScript。

执行简单的按钮翻转

一谈到 Web 页面上的按钮,Web 开发人员想要为按钮赋予的较为常见的功能就是翻转效果。翻转效果就是当终端用户将其鼠标置于 Web 页面的某个按钮上时(并不单击该按钮),该按钮的颜色和形状将发生改变。对于具有多个按钮的 Web 页面而言,该功能尤为有用,从使用角度而言这是很有用的,会在终端用户单击按钮之前通知其要对该按钮执行单击操作了。

在服务器控件出现之前,该操作很容易实现,现在,尽管有了服务器控件,也不是那么困难。执行类似操作的代码如下:

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 = "回发!"    End Sub</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>使用 JavaScript</title></head><body>    <form id="form1" runat="server">    <div>    <p>       <asp:ImageButton id="ImageButton1"         onmouseover="this.src='button2.gif'"         onclick="ImageButton1_Click"         onmouseout="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 = "回发!";  }</script><html xmlns="http://www.w3.org/1999/xhtml" ><head runat="server">    <title>使用 JavaScript</title></head><body>    <form id="form1" runat="server">    <div>    <p>       <asp:ImageButton id="ImageButton1"         onmouseover="this.src='button2.gif'"         onclick="ImageButton1_Click"         onmouseout="this.src='button1.gif'" runat="server"         ImageUrl="button1.gif"></asp:ImageButton>    </p>    <p>       <asp:Label id="Label1" runat="server" />    </p>    </div>    </form></body></html>

这次我们不通过 <body> 元素将 JavaScript 指定给服务器控件,而是使用控件的 onmouseoveronmouseout 事件。对于每个事件,我们均指定一个 JavaScript 值。onmouseover 事件表示终端用户将其鼠标置于控件上方的操作,而 onmouseout 表示终端用户将其鼠标从控件上方移开的操作。在本例中,我们希望当鼠标置于按钮上方时会显示一张图像,而在当加载页面后与当将鼠标从按钮移开后会显示原始图像。

如果您正在直接使用该类控件,而不是像我们在 <body> 元素中使用 JavaScript 时那样在 form 中指定控件,您可以使用 this 关键字,其后紧跟您试图更改的属性。

设置控件焦点

ASP.NET 2.0 现在包括了为其中的一个 HTML 表单元素设置(光标的)焦点的功能。在 ASP.NET 2.0 之前,您必须亲自使用 JavaScript 来完成同样的任务。例如,如果您的 ASP.NET 1.x 页面中有多个文本框,则可通过在页面的 <body> 标记中使用以下代码来使页面在加载后将焦点设置为第一个 TextBox 控件。

<body onload="document.forms[0]['TextBox1'].focus();">

通过使用该构造代码,当页面被加载后,包含 ID TextBox1 的元素将获得焦点,从而使终端用户能够开始直接输入文本,而无需通过鼠标来定位焦点。

ASP.NET 2.0 通过添加 Focus() 方法使得该任务变得非常简单。现在,您可以通过下面的代码来完成对 TextBox 控件的焦点设置:

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();  }

浏览器加载使用此方法的页面后,光标即已经被置于了文本框的内部,等待您开始键入文本。因此,您不必将鼠标移到相应的位置即可开始在表单中输入信息。Focus() 方法使您可以动态地将终端用户的光标置于指定的表单元素中(不仅仅是 TextBox 控件,而可以是从 WebControl 类派生而来的任何服务器控件)。

原文地址:https://www.cnblogs.com/symbol441/p/910306.html