c#
<%
@ Page Language
=
”C#”
%>
< script runat
=
”server”
>
protected
void
Page_Load(
object
sender, EventArgs e)
{
string myScript = @”function AlertHello() { alert(‘Hello ASP.NET’); }”;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
“MyScript”, myScript, true);
}
</ script >
< script
protected
{
string
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
“MyScript”,
}
</ script >
运行结果如下:
<
html
xmlns
=”http://www.w3.org/1999/xhtml”
>
< head >< title >
Adding JavaScript
</ title ></ head >
< body >
< form
method
=”post”
action
=”JavaScriptPage.aspx”
id
=”form1”
>
< div >
< input
type
=”hidden”
name
=”__VIEWSTATE”
value =”/wEPDwUKMTY3NzE5MjIyMGRkiyYSRMg+bcXi9DiawYlbxndiTDo=”
/>
</ div >
< script
type
=”text/javascript”
>
<!--
function AlertHello() { alert(‘Hello ASP.NET’); }// -->
</ script >
< div >
< input
type
=”submit”
name
=”Button1”
value
=”Button”
onclick
=”AlertHello();”
id =”Button1”
/>
</ div >
</ form >
</ body >
</ html >
< head >< title >
Adding
</ title ></ head >
< body >
< form
< div >
< input
value =”/wEPDwUKMTY3NzE5MjIyMGRkiyYSRMg+bcXi9DiawYlbxndiTDo=”
</ div >
< script
<!--
function
</ script >
< div >
< input
id =”Button1”
</ div >
</ form >
</ body >
</ html >
2.使用Page.ClientScript.RegisterStartupScript
RegisterStartupScript 方法与RegisterClientScriptBloc
如果你的页面中有如下代码:
<
asp:TextBox
ID
=”TextBox1”
Runat
=”server”
>
Hello ASP.NET
</
asp:TextBox
>
c#
protected
void
Page_Load(
object
sender, EventArgs e)
{
string myScript = @”alert(document.forms[0][‘TextBox1’].value);”;
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
“MyScript”, myScript, true);
}
此页面运行时会报错,原因是JavaScript function先于text box被安放于浏览器。因此JavaScript function找不到TextBox1。
{
string
Page.ClientScript.RegisterClientScriptBlock(this.GetType(),
“MyScript”,
}
c#
protected
void
Page_Load(
object
sender, EventArgs e)
{
string myScript = @”alert(document.forms[0][‘TextBox1’].value);”;
Page.ClientScript.RegisterStartupScript(this.GetType(),
“MyScript”, myScript, true);
}
这段代码把JavaScript function放置于ASP.NET page底部,因此JavaScript运行时它能找到TextBox1。
{
string
Page.ClientScript.RegisterStartupScript(this.GetType(),
“MyScript”,
}
3.使用Page.ClientScript.RegisterClientScriptInclude
许多开发者把JavaScript放置在.js文件中,使用RegisterClientScriptIncl
c#
string
myScript
=
“myJavaScriptCode.js”
Page.ClientScript.RegisterClientScriptInclude(“myKey”, myScript);
这将在ASP.NET页面产生如下结构:
Page.ClientScript.RegisterClientScriptInclude(“myKey”,
<script src=”myJavaScriptCode.js” type=”text/javascript”></script>