ASP.NET(1.0/1.1)给我们提供了一个开发WebControl的编程模型,于是我们摆脱了asp里面的include模式的复用方式。不过1.0/1.1提供的Web控件开发模型对于处理没有image、css等外部资源的组件还算比较得心应手,script虽然很多时候也是外部资源,但在开发控件的时候我们习惯把script使用Page.Register...Script()来嵌入模块,因为紧凑的东西更便于我们复用,用一个dll就可以解决问题又何必要节外生枝呢。
ASP.NET 2.0提供的Web Resources管理模型,很好的解决了image、css、script等外部资源的管理问题。现在只需要在solution explorer把资源文件的build action属性设为Embedded Resource。然后在assemblyinfo.cs里添加一句:
[assembly: WebResource(
"
WebCtrl.cutecat.jpg
"
,
"
image/jpg
"
)]
其实这个语句放任何cs文件里,保证放在最高级namespace外就行。 然后在程序中调用如下:
m_Image.ImageUrl
=
this
.Page.GetWebResourceUrl(
typeof
(WebCustom),
"
WebCtrl.cutecat.jpg
"
);
上面的语句返回给browser的代码是:
<
img
src
="WebResource.axd?a=pWebCtrl&r=WebCtrl.cutecat.jpg&t=632390947985312500"
style
="border-width:0px;"
/>
当然这个WebResource.axd是不存在的,它只是IIS中的一个ISAPI影射。 使用示例代码如下:
#region WebResource Demo
using System; using System.Collections.Generic; using System.ComponentModel; using System.Text; using System.Web.UI; using System.Web.UI.WebControls; [assembly: WebResource("WebCtrl.cutecat.jpg", "image/jpg")] namespace WebCtrl { [DefaultProperty("Text")] [ToolboxData("<{0}:WebCustom runat=server></{0}:WebCustom>")] public class WebCustom : WebControl { private string text; private Image m_Image; [Bindable(true)] [Category("Appearance")] [DefaultValue("")] public string Text { get { return text; } set { text = value; } } protected override void CreateChildControls() { m_Image = new Image(); this.Controls.Add(m_Image); } protected override void Render(HtmlTextWriter output) { m_Image.ImageUrl = this.Page.GetWebResourceUrl(typeof(WebCustom), "WebCtrl.cutecat.jpg"); this.RenderChildren(output); } } } #endregion
|
使用ASP.NET 2.0提供的WebResource管理资源
最新推荐文章于 2020-06-16 22:40:16 发布