当前位置导航:炫浪网>>网络学院>>网页制作>>ASP.NET教程

asp.net向客户端注册JavaScript脚本

  一般在sap.net中向客户端注册脚本有三种方法

  1.使用Literal控件在页面的任意位置注册脚本

  2.使用Response.Write()在页面的顶部注册脚本

  3.使用ClientScript.RegisterClientScriptBlock()或者ClientScript.RegisterStartupScript()分别在表单开始和结束的地方注册脚本

  下面给出一个使用了这三种方法的例子,新建一个apsx文件ScriptDemo.aspx

  <%@ Page Language="C#" AutoEventWireup="true" CodeFile="ScriptDemo.aspx.cs" Inherits="ScriptDemo" %>

  <!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>无标题页</title>

  </head>

  <body>

  <form id="form1" runat="server">

  <div>

  <asp:Literal ID="LiteralScript" runat="server"></asp:Literal></div>

  </form>

  </body>

  </html>

  可以看到我们在页面中仅仅放置了一个Literal控件,下面是.cs文件ScriptDemo.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 ScriptDemo : System.Web.UI.Page

  {

  protected void Page_Load(object sender, EventArgs e)

  {

  Response.Write("<script>alert('使用Response.Write()');</script>");

  Page.ClientScript.RegisterClientScriptBlock(Page.GetType(), "", "<script>alert('使用Page.ClientScript.RegisterClientScriptBlock()');</script>");

  Page.ClientScript.RegisterStartupScript(Page.GetType(), "", "<script>alert('使用Page.ClientScript.RegisterStartupScript()');</script>");

  LiteralScript.Text += "<script>alert('使用Literal控件');</script>";

  }

  }

相关内容
赞助商链接