在 .net 2.0 中向自定义控件添加 Web 资源






2.92/5 (4投票s)
本文描述了将 Web 资源(如 js、css、图像等文件)嵌入到自定义控件中的方法。
引言
在 .net 2.0 中,向自定义控件添加 Web 资源非常简单。以下代码将描述向自定义控件添加 Web 资源的方法。
使用代码
要向自定义控件添加 Web 资源,我们需要遵循以下步骤:
1. 将 Web 资源(如 JavaScript、样式表、图像文件)添加到您的自定义控件项目中。
3. 将“生成操作”属性设置为“嵌入资源”。[默认值设置为“内容”]
4. 在您的项目中添加对“System.Web”的引用。
5. 将以下内容添加到您的自定义控件中
using System.Web.UI;
6. 将“Web 资源”的程序集引用添加到您的项目中:[assembly: WebResource("ProjectName.ResourceFileName", "FileType")] 例如[assembly: WebResource ("CustomCtrlWithWebResource.MyCssFile.css", "text/css")] [assembly: WebResource ("CustomCtrlWithWebResource.MyJsFile.js", "text/javascript")]7. 添加以下行以添加 *.js 文件
//To add the JS file to the custom control string jsResource = "CustomCtrlWithWebResource.MyJsFile.js"; this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), jsResource);8. 对于其他资源,可以使用以下代码
//To add the CSS file to the custom control string cssResource = "CustomCtrlWithWebResource.MyCssFile.css"; string cssResourceURL = Page.ClientScript.GetWebResourceUrl(this.GetType(), cssResource); HtmlLink cssLink = new HtmlLink(); cssLink.Href = cssResourceURL; cssLink.Attributes.Add("rel", "stylesheet"); this.Page.Header.Controls.Add(cssLink);添加上述代码后,我们的“MyCustomCtrl.cs”文件将具有以下内容
using System; using System.Web.UI; using System.Web.UI.HtmlControls; [assembly: WebResource("CustomCtrlWithWebResource.MyCssFile.css", "text/css")] [assembly: WebResource("CustomCtrlWithWebResource.MyJsFile.js", "text/javascript")] namespace CustomCtrlWithWebResource { class MyCustomCtrl: Control { protected override void OnPreRender(EventArgs e) { base.OnPreRender(e); //To add the JS file to the custom control string jsResource = "CustomCtrlWithWebResource.MyJsFile.js"; this.Page.ClientScript.RegisterClientScriptResource(this.GetType(), jsResource); //To add the CSS file to the custom control string cssResource = "CustomCtrlWithWebResource.MyCssFile.css"; string cssResourceURL = Page.ClientScript.GetWebResourceUrl(this.GetType(), cssResource); HtmlLink cssLink = new HtmlLink(); cssLink.Href = cssResourceURL; cssLink.Attributes.Add("rel", "stylesheet"); this.Page.Header.Controls.Add(cssLink); } } }现在您可以向自定义控件添加所需的功能,并使用嵌入的资源(如“javascript 函数”、“cssClass”等)。