locked
How to add link to a css file in content page? RRS feed

  • Question

  • User546194788 posted

    How to add link to a css file in content page?

    There is no Head tag.

    Wednesday, June 11, 2008 4:11 PM

Answers

  • User-520527587 posted

     Try this

    In VB 

      

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Dim css As HtmlGenericControl
        css = New HtmlGenericControl
        css.TagName = "style"
        css.Attributes.Add("type", "text/css")
        css.InnerHtml = "@import ""/foobar.css"";"
        Page.Header.Controls.Add(css)
    End Sub
     

    In C#

      

    protected void Page_Init(object sender, System.EventArgs e)
    {
        HtmlGenericControl css;
        css = new HtmlGenericControl();
        css.TagName = "style";
        css.Attributes.Add("type", "text/css");
        css.InnerHtml = "@import \"/foobar.css\";";
        Page.Header.Controls.Add(css);
    }
     

    I hope that helps,
    Brendan 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 11, 2008 5:03 PM
  • User-1179452826 posted

    Masterpage:

     

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="webservicelogintest.Site1" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
        <asp:ContentPlaceHolder ID="head" runat="server">
        </asp:ContentPlaceHolder>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            
            </asp:ContentPlaceHolder>
        </div>
        </form>
    </body>
    </html>

     

     

    ContentPage:

     

    <%@ Page Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="webservicelogintest.floder.WebForm1" Title="Untitled Page" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
        <link ... />
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        <input type='text' />
        <input type='text'  />
    </asp:Content>

     

    That's right, you can place a content placeholder in the head :)

    In VS 2005, it'll show an error (squigly line under the content placeholder tag). Don't worry, it'll compile and run fine. In VS 2008, it doesn't even give that warning.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 11, 2008 11:20 PM
  • User-1179452826 posted

    @alsakaf:

    you should avoid putting the css link in he body (as will happen if you put the link in the contentplaceholder where all the other html goes). You should put a contentplaceholder in the head of the masterpage and in the contentpage, put the link in the content for the head contentplaceholder. That's the recommended practice, straight from scott gu's blog :)

    [btw...that's what my code above does]

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 12, 2008 1:34 AM
  • User-1179452826 posted

    Two options:

    1. Use a "client" side rooted uri. So src='/folder/file.css' instead of src='folder/file.css'.

    2. Use the content placeholder trick I mentioned above and in the masterpage, set <head runat='server'> Setting head to runat server should make link tags resolve ~/.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 12:45 AM
  • User-1179452826 posted

    Ah yes... ~/ references with runat='server' get resolved only for the page where the head is specified. In the content page, you should be able to specify src='/folder/file.css'. This will appear as src='/folder/file.css' in the output html. Since that starts with a '/', the browser will look for the file file.css in the folder called 'folder' at the root of the website. Isn't that what you need? 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 7:40 AM
  • User-1179452826 posted

    If you're css file is called file.css and is in a folder called folder and your output html has '/folder/file.css' in the head, then it should resolve fine.

    Could you post the head of your output html for us?

    Also, I'd recommend you create a folder called css in the root of your application and put all css content there. That way, you can use src='/css/master.css' and src='/css/content-specific.css' in your pages and it should work. Your approach of putting the css file in the same place as the aspx could fail if you had certain role requirements on the folder containing the css.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 8:10 AM
  • User-1179452826 posted

    Could you please show us the following:

    1. The <head> section of your OUTPUT HTML.

    2. The folder structure.

    3. The url you type in the browser to get to the page concerned.

    That will give us better info as to why ResolveClientUrl works but src='/folder/file.css' doesn't. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 1:59 PM
  • User-1972033802 posted

    Oh dear.  OK, I figured it out.  You were right - my problem was that my project had a virtual path set up other than "/" (i.e. "/projectname").  That was the reason why "/folder/file.css" did not match "/projectname/folder/file.css".  Now that I reset the virtual path to "/", it works exactly as you advertised, both locally and on the server.

    Funny, I can't remember putting the virtual path in, but it's an older project so who knows.

    What I'm taking from this adventure is that if you are using virtual path for your project, you'll have to ResolveClientUrl() or start with "/VirtualPath", otherwise you can just do "/folder/file.css".

    Thanks, HeartattacK, for sticking around.  I actually created an empty new project to test it because my <head> output worked fine - I guess you don't need me to show the code here anymore?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 8:04 PM

All replies

  • User-520527587 posted

     Try this

    In VB 

      

    Protected Sub Page_Init(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Init
        Dim css As HtmlGenericControl
        css = New HtmlGenericControl
        css.TagName = "style"
        css.Attributes.Add("type", "text/css")
        css.InnerHtml = "@import ""/foobar.css"";"
        Page.Header.Controls.Add(css)
    End Sub
     

    In C#

      

    protected void Page_Init(object sender, System.EventArgs e)
    {
        HtmlGenericControl css;
        css = new HtmlGenericControl();
        css.TagName = "style";
        css.Attributes.Add("type", "text/css");
        css.InnerHtml = "@import \"/foobar.css\";";
        Page.Header.Controls.Add(css);
    }
     

    I hope that helps,
    Brendan 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 11, 2008 5:03 PM
  • User-1179452826 posted

    Masterpage:

     

    <%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site1.master.cs" Inherits="webservicelogintest.Site1" %>
    
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    
    <html xmlns="http://www.w3.org/1999/xhtml" >
    <head runat="server">
        <title>Untitled Page</title>
        <asp:ContentPlaceHolder ID="head" runat="server">
        </asp:ContentPlaceHolder>
    </head>
    <body>
        <form id="form1" runat="server">
        <div>
            <asp:ContentPlaceHolder ID="ContentPlaceHolder1" runat="server">
            
            </asp:ContentPlaceHolder>
        </div>
        </form>
    </body>
    </html>

     

     

    ContentPage:

     

    <%@ Page Language="C#" MasterPageFile="~/Site1.Master" AutoEventWireup="true" CodeBehind="WebForm1.aspx.cs" Inherits="webservicelogintest.floder.WebForm1" Title="Untitled Page" %>
    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="server">
        <link ... />
    </asp:Content>
    <asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="server">
        <input type='text' />
        <input type='text'  />
    </asp:Content>

     

    That's right, you can place a content placeholder in the head :)

    In VS 2005, it'll show an error (squigly line under the content placeholder tag). Don't worry, it'll compile and run fine. In VS 2008, it doesn't even give that warning.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Wednesday, June 11, 2008 11:20 PM
  • User-1401220735 posted

    Hi Try this,

    Add link inside the ContentPlaceHolder Tag as below code..

    <asp:Content ID="cphRequestForm" ContentPlaceHolderID="cphCommbuilder" runat="server">

    <link href="Styles/StyleSheet.css" type="text/css" rel="stylesheet"/>

    Your HTML goes here...

    Hope this helps.

    If this post helps you, Click Mark as Answer

    Thursday, June 12, 2008 12:34 AM
  • User-1179452826 posted

    @alsakaf:

    you should avoid putting the css link in he body (as will happen if you put the link in the contentplaceholder where all the other html goes). You should put a contentplaceholder in the head of the masterpage and in the contentpage, put the link in the content for the head contentplaceholder. That's the recommended practice, straight from scott gu's blog :)

    [btw...that's what my code above does]

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Thursday, June 12, 2008 1:34 AM
  • User-657704042 posted

    <link rel="stylesheet" src="path of the stylesheet" type="text/css">

    just add the above line in between the head tag.

    Thursday, June 12, 2008 9:09 AM
  • User546194788 posted

    I tested Brendan's way, it works fine.

    Thank all of you.

    Thursday, June 12, 2008 9:41 AM
  • User1514979238 posted

    This is an other way

    protected void Page_Init(object sender, EventArgs e)
            {
                HtmlLink css1 = new HtmlLink();
                css1.Href = "css/fancyforms.css";
                css1.Attributes["rel"] = "stylesheet";
                css1.Attributes["type"] = "text/css";
                css1.Attributes["media"] = "all";
                Page.Header.Controls.Add(css1);
            }

    Jaimir G.
    http://msmvps.com/blogs/jaimirg/

    Wednesday, December 2, 2009 8:16 PM
  • User9329584 posted

    bt sir how we can use css other coding in asp.net.

    means after that link what is the next step.


    please provide full information of this code.


    thanks!!!!!

    Monday, May 31, 2010 8:47 AM
  • User1514979238 posted

    Hi

    After link a css style file using any of the mechanisms described here, you can use styles defined in this file to apply it on any visual element on your web page.

    Example:

    Content file css:

    .header
    {
        ;
        margin: 0px;
        padding: 0px;
        background: #4b6c9e;
        width: 100%;
    }
    


    Direct use in the markup:

    <div class="header">My ASP.NET Application</div>
    

    Use in server code:

    this.TituloLabel.CssClass = "header";



     

    Tuesday, June 1, 2010 9:52 AM
  • User-1972033802 posted

    This is great and absolutely right.
    I have one issue though - how does one make the css links resolve rooted URIs (that is to say starting with "~/")??
    Normally, if I want a HTML control to resolve links, I make it runat="server". But with <link> I haven't found a way. Whether or not I make it runat="server", my resulting page code shows "~/..." and the stylesheet is not found and thus not applied.
    Not a huge issue right now, but I'd like to know whether there's a way.

    Friday, September 3, 2010 4:02 PM
  • User-1179452826 posted

    Two options:

    1. Use a "client" side rooted uri. So src='/folder/file.css' instead of src='folder/file.css'.

    2. Use the content placeholder trick I mentioned above and in the masterpage, set <head runat='server'> Setting head to runat server should make link tags resolve ~/.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 12:45 AM
  • User-1972033802 posted

    Thanks HeartattacK for the quick response.

    I took a look at it again and these are my findings in .NET 4.0:

    1. Setting "head" to runat="server" doesn't help with link resolution. Whether my <link> is "/folder/file.css" or "~/folder/file.css", in the resulting HTML it appears just as entered, even with the tilde, and in neither case is applied.  It only works when provided as "file.css".
      Although I must say that the link in the master page resolves perfectly to a relative path (e.g. "../master.css").
    2. This is the case whether or not the <link> in the content is runat="server".  I'm quite confused here, because I can't think of another way to force path resolution other than some dynamic code tag <%%>.

    My code is something like this:

    Master (resolves OK):

    <head runat="server">
      <title>Hello</title>
      <asp:ContentPlaceHolder ID="head" runat="server">
      </asp:ContentPlaceHolder>
      <link href="~/master.css" rel="stylesheet" type="text/css" runat="server" />
    </head>


    Content page (can't get to resolve):

    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
      <link href="~/folder/file.css" rel="stylesheet" type="text/css" runat="server" />
    </asp:Content>

    Thanks again,
    R

    Saturday, September 4, 2010 7:13 AM
  • User-1179452826 posted

    Ah yes... ~/ references with runat='server' get resolved only for the page where the head is specified. In the content page, you should be able to specify src='/folder/file.css'. This will appear as src='/folder/file.css' in the output html. Since that starts with a '/', the browser will look for the file file.css in the folder called 'folder' at the root of the website. Isn't that what you need? 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 7:40 AM
  • User-1972033802 posted

    You're right, that's exactly what I need! But when I put this into the content page:

    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
        <link href="/folder/file.css" rel="stylesheet" type="text/css"/>
    </asp:Content>

    as you propose, the resulting HTML is:

    <link href="/folder/file.css" rel="stylesheet" type="text/css"/>

    and it won't apply the stylesheet in the browser.

    Did I mention that my content page was "~/folder/content.aspx"?  I need it to apply "~/master.css" as well as "~/folder/file.css".  Could that have an impact on what I'm trying to achieve?

    My point is that I'd like to safeguard appearance if I ever decide to move the content pages to other folders, etc.  That's why I am looking for a solution how to anchor the stylesheets in XHTML so that I don't have to change code/move stylesheets when I move my content pages.

    PS: I can tell that adding runat="server" to the content's <link> has an effect, because it renders the link as <link></link> as opposed to <link/> when I omit runat="server".  However, paths don't resolve in any of the cases I've tried out and described.

    Saturday, September 4, 2010 8:00 AM
  • User-1179452826 posted

    If you're css file is called file.css and is in a folder called folder and your output html has '/folder/file.css' in the head, then it should resolve fine.

    Could you post the head of your output html for us?

    Also, I'd recommend you create a folder called css in the root of your application and put all css content there. That way, you can use src='/css/master.css' and src='/css/content-specific.css' in your pages and it should work. Your approach of putting the css file in the same place as the aspx could fail if you had certain role requirements on the folder containing the css.

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 8:10 AM
  • User-1972033802 posted

    OK, so what I've ended up doing for now is put the following into the content page:

    <asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
        <link  href='<%= ResolveClientUrl("~/folder/file.css") %>' rel="stylesheet" type="text/css"/>
    </asp:Content>

    This approach only works when your <link> tag is NOT runat="server".

    I understand and agree with your recommendation to put everything into a "css" folder, but my "folder" is the same as any other generic folder and there are no differences in permissions or otherwise.  Thus, I am not concerned with that being the issue right now.

    Also I tried to completely move file.css to a "css" folder and use your approach, but it just didn't work with "/css/file.css" - it only worked with "../css/file.css", I think because my content page is in a subfolder.

    When you use ResolveClientUrl in the <link> tag, it works and it does explicitly what I've been trying to achieve implicitly and failed.  It is not as aesthetically pleasing as some XHTML trick, but it works exactly as I expect/want it to.

    If you do use runat="server", the href will actually get HtmlEncode'd and that is complete mess.

    For some reason, HeartattacK, I simply couldn't make my browser (either IE8 or Chrome) trace the stylesheet correctly when supplying a path starting "/" (i.e. "/folder/file.css") from a content page that sits in a subfolder...

    Saturday, September 4, 2010 10:29 AM
  • User-1179452826 posted

    Could you please show us the following:

    1. The <head> section of your OUTPUT HTML.

    2. The folder structure.

    3. The url you type in the browser to get to the page concerned.

    That will give us better info as to why ResolveClientUrl works but src='/folder/file.css' doesn't. 

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 1:59 PM
  • User-1972033802 posted

    Oh dear.  OK, I figured it out.  You were right - my problem was that my project had a virtual path set up other than "/" (i.e. "/projectname").  That was the reason why "/folder/file.css" did not match "/projectname/folder/file.css".  Now that I reset the virtual path to "/", it works exactly as you advertised, both locally and on the server.

    Funny, I can't remember putting the virtual path in, but it's an older project so who knows.

    What I'm taking from this adventure is that if you are using virtual path for your project, you'll have to ResolveClientUrl() or start with "/VirtualPath", otherwise you can just do "/folder/file.css".

    Thanks, HeartattacK, for sticking around.  I actually created an empty new project to test it because my <head> output worked fine - I guess you don't need me to show the code here anymore?

    • Marked as answer by Anonymous Thursday, October 7, 2021 12:00 AM
    Saturday, September 4, 2010 8:04 PM
  • User-1179452826 posted

    That was precisely the I asked for those three things...it seemed very much like a virtual path issue...glad you resolved it [:)]

    Saturday, September 4, 2010 8:24 PM
  • User1514979238 posted

    Hi,

    You can use this option too:

    protected void Page_Init(object sender, EventArgs e)
            {
                HtmlLink css1 = new HtmlLink();
                css1.Href = ResolveUrl("~/css/fancyforms.css");
                css1.Attributes["rel"] = "stylesheet";
                css1.Attributes["type"] = "text/css";
                css1.Attributes["media"] = "all";
                Page.Header.Controls.Add(css1);
            }

    Note: css1.Href = ResolveUrl("~/css/fancyforms.css");

     

    Monday, September 6, 2010 1:05 PM