天天看點

ASP.NET中注冊用戶端腳本的三種方式

1. RegisterClientScriptBlock

  把Javascript函數放在頁面頂部

代碼如下:

protected void Page_Load(object sender, EventArgs e)

{

  string myScript = @"function AlertHello() { 

                      var oText = document.getElementById('TextBox1');

                      alert(oText.value); }";

  Page.ClientScript.RegisterClientScriptBlock(this.GetType(),

               "MyScript", myScript, true);

}

生成的html代碼如下:

<html xmlns="http://www.w3.org/1999/xhtml" >

...

<body>

<form>

... 

<script type="text/javascript"> 

//<![CDATA[

function AlertHello() { 

  var oText = document.getElementById ('TextBox1');

  alert(oText.value); }//]]>

</script>

<input name="TextBox1" type="text"  id="TextBox1" />

<input type="submit" name="Button1" value="Button" onclick="AlertHello();" id="Button1" />

</form>

</body>

</html>

2. RegisterStartupScript

把Javascript函數放在頁面底部

  string myScript = @"document.getElementById('TextBox1').value = 'Hello ASP.NET.';

                      var oText = document.getElementById('TextBox1');

                      alert(oText.value); ";

  Page.ClientScript.RegisterStartupScript(this.GetType(),

<html>

...        

<input name="TextBox1" type="text" id="TextBox1" />

document.getElementById('TextBox1').value = 'Hello ASP.NET.';

var oText = document.getElementById('TextBox1');

alert(oText.value); //]]>

3. RegisterClientScriptInclude

注冊外部的Javascript腳本檔案

  string myScript = "../JS/myJavaScriptCode.js";

  Page.ClientScript.RegisterClientScriptInclude("MyScript", myScript);

Javascript代碼如下:

function AlertHello() {

    var oText = document.getElementById('TextBox1');

    alert(oText.value);

HTML中調用如下:

<asp:Button ID="Button1" Runat="server" Text="Button"

            OnClientClick="AlertHello()" />

它也是把script腳本放在代碼底部

繼續閱讀