The Will Will Web

記載著 Will 在網路世界的學習心得與技術分享

如何將 JavaScript, CSS, Images 檔案內含在 .NET 組件裡

通常內嵌在組件的資源可以透過 ASP.NET 內建的 WebResource.axd 這個 HTTP Handler 取得,所以你才會在查看 ASP.NET 頁面產生的原始碼的時候看到許多奇怪的網址,裡面就是包含這個 WebResource.axd,而這些透過 WebResource.axd 抓到的檔案就是 Handler 去讀取組件(*.dll)的資源抓回來的內容,可能是任何型態的檔案,比較常見的有: JavaScript、各種圖檔或 css 檔案。

這種內嵌式的資源檔最大的好處就是簡化網頁設計的複雜度,如果我們要設計一個 WebControl 用在頁面上,而部屬(Deploy)這個 WebControl 的時候又需要用到一些外部的檔案(例如: 圖檔),如果不包含在組件理的話,就要在使用這個 WebControl 的時候 "記得" 將圖檔複製到目錄中,如果 "忘記" 的話就會破圖了!

如果你要將這些資源檔內嵌在你的 WebControl 專案中的話,有以下的步驟:

1. 先將需要內嵌的檔案全部加入到你的專案中。

2. 修改 AssemblyInfo.cs 檔案,手動將這些內嵌的資源檔定義到組件資訊去

[code:c#]
[assembly: System.Web.UI.WebResource("Doggy.UI.WebControls.MyControl.MyScript.js", "text/js")];
[assembly: System.Web.UI.WebResource("Doggy.UI.WebControls.MyControl.imgButton.gif", "img/gif")];
[assembly: System.Web.UI.WebResource("Doggy.UI.WebControls.MyControl.TextBox1.css", "text/css")];
[/code]

備註: 所有的檔名都要用以下這種格式表示才行!但是在專案裡的檔名不用改成這樣!

        DefaultNamespace.Filename.Extension

3. 在你的 *.cs 檔中使用這些內嵌的資源檔

[code:c#]
// 內嵌 JavaScript
string strJsLoc =Page.ClientScript.GetWebResourceUrl(this.GetType(), "Doggy.UI.WebControls.MyControl.MyScript.js");
Page.ClientScript.RegisterClientScriptInclude("Doggy.UI.WebControls.MyControl.MyScript.js", strJsLoc);

// 內嵌影像檔
Image img = new Image();
img.ImageUrl = Page.ClientScript.GetWebResourceUrl(this.GetType(), "Doggy.UI.WebControls.MyControl.imgButton.gif");

// 內嵌 CSS 檔 ( 記得頁面中的 <head> 標籤要加上 runat="server" 才行!
string link_template = "<link rel='stylesheet' text='text/css' href='{0}' />";
string link_location = Page.ClientScript.GetWebResourceUrl(this.GetType(), "Doggy.UI.WebControls.MyControl.TextBox1.css");
LiteralControl ltlLink = new LiteralControl(String.Format(link_template, link_location));
((HtmlControls.HtmlHead) Page.Header).Controls.Add(ltlLink);
[/code]

如果看不懂的話,也沒關係,這裡有更清楚的文章說明:

留言評論