自定义控件把脚本文件编译为内嵌资源实例
- .Net编程
- 2007-11-24
- 114热度
- 0评论
我们在开发自定义的Web控件中,往往需要使用到系列客户端脚本代码,当我们发布控件时,为了方便发布和使用,一般不直接发布脚本文件,而是将脚本文件编译为内嵌的资源,然后从资源中读取脚本并注册。当然在ASP.NET里这个步骤比较简单,关键的是保证脚本文件的编译属性为"内嵌资源".
public class ScriptControl : Control {
/// <summary>
/// Register Client Script Block
/// </summary>
/// <param name="control">custom web control</param>
/// <param name="scriptfile">resource script file name</param>
public void RegisterScript(string scriptfile){
if (!this.Page.IsClientScriptBlockRegistered(scriptfile)) {
StreamReader reader = Res.GetStream(this.GetType(),scriptfile);
using(reader){
string script
= "<script language="javascript" type="text/javascript">rn<!--rn"
+ reader.ReadToEnd()
+ "rn//-->rn</script>";
this.Page.RegisterClientScriptBlock(scriptfile, script);
}
}
}
}
public class Res {
public static StreamReader GetStream(Type type,string name){
//Assembly assembly = Assembly.GetAssembly(type);
Assembly assembly = type.Assembly;
Stream stream = assembly.GetManifestResourceStream(type,name);
return new StreamReader(stream);
}
}
[DefaultProperty("Text"),
ToolboxData("<{0}:ShowDialogListBox runat=server></{0}:ShowDialogListBox>")]
public class ShowDialogListBox : ScriptControl {
......
protected override void OnInit(EventArgs e) {
this.RegisterScript("EnDeListBox.js");
}
......
}