[ASP.NET]在自訂控制項中包含css

來源:互聯網
上載者:User

在自訂控制項中包含css通常的做法是這樣的:

string csslink = "<link href='" + url + "' rel='stylesheet' type='text/css' />";LiteralControl include = new LiteralControl(csslink);page.Header.Controls.Add(include);

但以上程式有一個問題,就是當Header中存在 <%%>的代碼塊的時候,會出現執行階段錯誤,解決此種問題的方法是,既不能要求使用者(使用控制項的人)不在Header中使用代碼塊<%%>,也不能直接Page.Controls.Add(include),因為這同樣會出現執行階段錯誤

我的做法如下:

public static class ControlExtension{    public static void IncludeCss(this Control control,String webResouce)    {        String cssUrl = control.Page.ClientScript.GetWebResourceUrl(control.GetType(), webResouce);        LiteralControl cssLink = new LiteralControl("<link href='" + cssUrl + "' rel='stylesheet' type='text/css' />");        control.Controls.Add(cssLink); //加到自訂控制項本身    }}

使用舉例,在一個複全控制項中:

protected override void CreateChildControls(){    this.IncludeCss("myNamespace.cssDirectory.my.css"); //包含指定資源代表的css檔案    //其它子控制項代碼,此處略}

開啟頁面查看源檔案:

<span id="myCustomControl"><link href='/WebResource.axd?d=T-gej6K8_w1LkIj4bdXyqrRrlMm-k0JVbBNwrI0dxqXiG_WAIlV2hihdU42EmH1cVUHmP8WzxmtYZOJYBm_7itbs3R2ivvV161BQMXNp1sI4lSTAuMJXbJp_OT2OaVRaF58CsLcgb_QGMvPsFTBDBLtXKZ0Y9mk0_W0m0AND0gNwD7SC0&t=634680192080902436' rel='stylesheet' type='text/css' />

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.