我需要添加指向ASPX頁面頭部的鏈接,該鏈接基於從Master Page的Page_Load()
調用的服務器端函數。整個網站使用相同的主頁面。有條件地添加外部CSS/Javascript鏈接
這樣做的最好方法是什麼?
一個<asp:Literal>
控制在<head>
?
我需要添加指向ASPX頁面頭部的鏈接,該鏈接基於從Master Page的Page_Load()
調用的服務器端函數。整個網站使用相同的主頁面。有條件地添加外部CSS/Javascript鏈接
這樣做的最好方法是什麼?
一個<asp:Literal>
控制在<head>
?
也許爲時已晚,但下面的方法具有優點,即相同的腳本永遠不會添加兩次。
public static void RegisterClientScriptInclude(Page page, string name, string url)
{
Type cstype = page.GetType();
// Get a ClientScriptManager reference from the Page class.
ClientScriptManager cs = page.ClientScript;
// Check to see if the include script exists already.
if (!cs.IsClientScriptIncludeRegistered(cstype, name))
{
cs.RegisterClientScriptInclude(cstype, name, page.ResolveClientUrl(url));
}
}
如果您在需要的基礎上添加來自不同用戶控件的外部JavaScript文件,那麼就派上用場了。
有很多方法可以做到這一點:
在你Page_Load
方法,程序訪問你的母版頁的標題,如:
HtmlGenericControl style = new HtmlGenericControl("link");
style.Attributes.Add("href", "path-to-your-style");
style.Attributes.Add("rel", "stylesheet");
style.Attributes.Add("type", "text/css");
this.Page.Header.Controls.AddAt(0, style);
第二種方式是把runat='server'
屬性上您的頭部條件樣式以及您的Page_Load
方法中,將其可見性打開或關閉:
<link type='text/css' rel='stylesheet' href='path-to-css-file'
runat='server' id='cssFile' />
然後在Page_Load
您有:
if (conditionIsNotMet)
{
cssFile.Visible = false;
}
(1)時髦,看起來比文字更清潔 – Greg
我已經成功做這樣的事情過去。
<link rel="Stylesheet" type="text/css" href="<%= System.Configuration.ConfigurationManager.AppSettings["dhxStyle"] %>" />
這可以用來添加到外部JavaScript文件的鏈接嗎?我只用它來添加原始的JS代碼。 – Greg
是的,它可以。 RegisterClientScriptInclude是關鍵。 – Remy
啊,很好 – Greg