programmatically add stylesheet and javascript references to asp.net masterpage
I'm using Lightbox but i only want the references to the stylesheet and javascript files to be in the masterpage header on one pa开发者_Go百科ge on the site (the page that uses lightbox). how do I programmatically add references to the stylesheet and javascript files in the page load?
the stylesheet is the 'css' folder and the three javascript files are a 'js' folder
try...
Page.ClientScript.RegisterClientScriptInclude("JScripts", ResolveUrl("~/js/JScripts.js"));
Add two placeholders ("JsPlaceholder" and "CSSPlaceholder") to your header on master page and call those methods:
public void AddJavascriptFile(string path)
{
PlaceHolder p = (PlaceHolder)Page.Header.FindControl("JsPlaceholder");
p.Controls.Add(new LiteralControl(string.Concat("<script type='text/javascript' src='", path, "'></script>\n")));
}
public void AddCssFile(string urlPath)
{
HtmlLink cssLink = new HtmlLink();
cssLink.Href = path;
cssLink.Attributes.Add("rel", "stylesheet");
cssLink.Attributes.Add("type", "text/css");
PlaceHolder p = (PlaceHolder)Page.Header.FindControl("CssPlaceholder");
p.Controls.Add(cssLink);
}
Try (in C# but you should get the idea):
protected override void OnLoad(EventArgs e)
{
base.OnLoad(e);
HtmlLink cssLink = new HtmlLink();
//Create and configure the CSS link.
cssLink.Attributes.Add("rel", "Stylesheet");
cssLink.Attributes.Add("type", "text/css");
cssLink.Href = "~/Path/To/File.css";
//Add the CSS link to the page header.
this.Header.Controls.Add(cssLink);
//Add a script include to the page's ClientScript.
this.ClientScript.RegisterClientScriptInclude("NameOfScript", this.ResolveUrl("~/Path/To/File.js"));
}
you can do it like this
added this to your header:
<asp:placeholder runat="server" id="lightbox" visible="false">
<link rel="stylesheet" href="/css/style.css" />
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.5.1/jquery.min.js"</script>
</asp:placeholder>
and from your codebehind set
lightbox.visible=true;
You should also note that normally you want to keep as much html on the page instead of having it in your codebehind so it will be easy for the designer to make changes
精彩评论