在使用ASP.NET的时候,经常需要使用客户端脚本。一般情况下我们都是直接在.aspx文件中编辑脚本或是包含.js文件。但是有些情况下我们需要动态的添加客户端脚本,为此ClientScriptManager类中提供了大量这样的方法。由于本人多数是使用非动态方式创建的,所以下面这些简要的总结若有不到之处,尽请指出。
1、RegisterStartupScript:该方法添加的脚本块在页面加载完成但页面的OnLoad事件引发之前执行,一般而言是一次性的脚本内容。由于这个方法注册的脚本时放在页面的底部,因此可以让我们很方便的使用页面中的元素。
2、RegisterClientScriptBlock:该方法在已呈现的页的顶部添加一个脚本块。由于这个方法放在页面的顶部,所以页面的中元素可能不能正常调用。该方法一般用于注册客户端事件。
3、RegisterClientScriptInclude:该方法主要用于注册一个脚本包含。除此之外它和RegisterClientScriptBlock的注意事项雷同。
4、RegisterOnSubmitStatement:该方法主要用于注册一个与OnSubmit事件绑定的脚本。
关于方法1-4的简单例子:
5、GetPostBackEventReference和GetPostBackClientHyperlink:返回一个可以在客户端事件中使用的字符串,以便回发到服务器。总体上两者的用途是一样的,主要区别在于:前者返回的串以 "javascript:" 打头,而后者则没有。
客户端文件内容:
<input name="myButton" type="button" id="myButton" value="Click" onclick="__doPostBack('__Page','myButton')" /> <a href="javascript:__doPostBack('__Page','myAnchor')" id="myAnchor">Link</a>
还有其他部分方法有待补充...