views:

60

answers:

2

How do I include CSS reference in only certain pages on my asp.net website? If I include the reference in my master page, all pages of the website share the CSS reference.

+1  A: 

You can use more than one Master page on your site.

You can also use nested master pages. The Top level might have the general site structure, and then one Master nested master page for each of your different areas.

When you right click your project and select Add, you choose the option WebContentForm, instead of WebForm. Then you can select the appropriate masterpage.

In your nested masterpages, you set the MasterPageFile equal to your top level masterpage.

Edit When combined with @Marko's approach you could have the following...

The advantage here is that all of your overrides only have to be written once.

Top Level MasterPage:

<head>
    <asp:ContentPlaceHolder ID="Stylesheets" runat="server">
        <link rel="stylesheet" href="/css/default.css" type="text/css" />
    </asp:ContentPlaceHolder>
</head>

Nested MasterPage with no override

<%@ Page Language="C#" MasterPageFile="~/Site.master"%>
//don't reference the Stylesheets ContentPlaceHolder and the default is rendered

Nested MasterPage One with override.css

<%@ Page Language="C#" MasterPageFile="~/Site.master"%>
<asp:Content ID="Content1" ContentPlaceHolderID="Stylesheets" runat="server">
    <link rel="stylesheet" href="/css/override.css" type="text/css" />
</asp:Content>

Nested MasterPage Two with secondOverride.css

<%@ Page Language="C#" MasterPageFile="~/Site.master"%>
<asp:Content ID="Content1" ContentPlaceHolderID="Stylesheets" runat="server">
    <link rel="stylesheet" href="/css/secondOverride.css" type="text/css" />
</asp:Content>

Then, just set the appropriate master page on any of your web forms.

Daniel Dyson
Is'nt there any way to just include the CSS reference in my page which inherits the master page ?
Popo
Yes, see Marko's answer. A combination of the two approaches might work perfectly.
Daniel Dyson
+3  A: 

Just add a CSS ContentPlaceHolder with a default value in it.

Basically, the CSS file you specify as default will be included unless you override that placeholder with an <asp:Content /> tag from a child page.

Your Master Page should look something like this.

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

Then from any pages using that Master Page, you can simply override that with a different stylesheet.

On (example) AboutUs.aspx

<asp:Content ID="Content1" ContentPlaceHolderID="Stylesheets" runat="server">
    <link rel="stylesheet" href="/css/form.css" type="text/css" />
</asp:Content>
Marko
+1 I actually like this solution better than my suggestion. I have used it before and it is a good option. I will leave my answer though, as someone might find it helpful.
Daniel Dyson