0

I have a master page file and I have always added additional style sheets pragmatically using Page.Header.Controls.Add etc. But we have a client that wants the css files in a specific place, so I noticed that in the head section there is a
<asp:ContentPlaceHolder ID="HeadContent" runat="server">

so I thought I could just add it into there.

I have tried

ContentPlaceHolder blar = (ContentPlaceHolder)Master.FindControl("HeadContent");
blar.Controls.Add(css); 

But nothing appears, can anyone help?

Satpal
  • 132,252
  • 13
  • 159
  • 168
andrew slaughter
  • 1,069
  • 5
  • 19
  • 34

2 Answers2

0

U can add your css file like that;

ContentPlaceHolder blar = (ContentPlaceHolder)Master.FindControl("HeadContent");
HtmlLink css= new HtmlLink();
css.Attributes.Add("rel", "stylesheet");
css.Attributes.Add("type", "text/css");
css.Href = "/Styles/site.css";
blar.Controls.Add(css); 
CocLn
  • 742
  • 10
  • 15
0

Check out the answer to this question: https://stackoverflow.com/a/2969360/1372321

It seems to do what you want :)

Update

To add content at a specific place in the header, and you are using .Net 4.5, you can use the System.Web.Optimatization API and bundle the styles. Then in your head, you can use the provided control:

<webopt:BundleReference runat="server" Path="~/Content/css" /> 

You can see an example of this in the default WebForms project template.

If you're using an older version of .Net, you can use content placeholder in your master page, and then add controls to that specific placeholder like so:

In master page head

<asp:ContentPlaceHolder runat="server" ID="HeadContent" />

In aspx page

<asp:Content runat="server" ContentPlaceHolderID="HeadContent">
    <asp:PlaceHolder runat="server" ID="placeHolderHead"></asp:PlaceHolder>
</asp:Content>

Then you can simply add the Link controls to the placeholder programatically.

Community
  • 1
  • 1
  • Im currently using Page.Header.Controls.Add() however that places the css just before the closing head tag, my client wants me to put the css file after the other css files and before the js files used on the page – andrew slaughter Jul 16 '13 at 10:20