.NET2.0中客户端脚本的使用

在.NET2.0中,新加了一个类:ClientScriptManager,该类让我们可以在服务器端编写客户端脚本,而在执行的时候不用回发。一个典型的小例子:

//服务器端控件,调用客户端脚本
if (Request.Browser.SupportsCallback)//验证浏览器是否支持
{
//不用回发的客户端脚本,参数1是脚本的类型,参数2是脚本的关键字(用来区分),参数3是执行的脚本内容
Page.ClientScript.RegisterStartupScript(this.GetType(), "startup", "<script>alert('sss')</script>");
}
else
{
//原来的交互
Response.Write("<script>alert('ddd')</script>");
}
//客户端控件,在服务器端调用动态根据程序运行的内容执行客户端脚本
<%@ Page Language="C#"%>
<script runat="server">
public void Page_Load(Object sender, EventArgs e)
{
// Define the name and type of the client scripts on the page.
String csname1 = "PopupScript";
String csname2 = "ButtonClickScript";
Type cstype = this.GetType();

// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = Page.ClientScript;

// Check to see if the startup script is already registered.
if (!cs.IsStartupScriptRegistered(cstype, csname1))
{
String cstext1 = "alert('Hello World');";
cs.RegisterStartupScript(cstype, csname1, cstext1, true);
}

// Check to see if the client script is already registered.
if (!cs.IsClientScriptBlockRegistered(cstype, csname2))
{
StringBuilder cstext2 = new StringBuilder();
cstext2.Append("<script type=text/javascript> function DoClick() {");
cstext2.Append("Form1.Message.value='Text from client script.'+Form1.ok.value} </");
cstext2.Append("script>");
cs.RegisterClientScriptBlock(cstype, csname2, cstext2.ToString(), false);
}
}
</script>
<html>
<head>
<title>ClientScriptManager Example</title>
</head>
<body>
<form id="Form1"
runat="server">
<input type="text" id="Message"> <input id ="ok" type="button" value="ClickMe" onclick="DoClick()">
</form>
</body>
</html>

你可能感兴趣的:(.net)