Add CSS references to page's <head> from a partial view

kristian picture kristian · Nov 18, 2010 · Viewed 9k times · Source

Is there a way to add CSS references to a page from a partial view, and have them render in the page's <head> (as required by the HTML 4.01 spec)?

Answer

Rich Turner picture Rich Turner · Feb 13, 2011

If you're using MVC3 & Razor, the best way to add per-page items to your section is to: 1) Call RenderSection() from within your layout page 2) Declare a corresponding section within your child pages:

/Views/Shared/_Layout.cshtml:

<head>
    <!-- ... Rest of your head section here ... ->
    @RenderSection("HeadArea")
</head>

/Views/Entries/Index.cshtml:

@section HeadArea {
    <link rel="Stylesheet" type="text/css" href="/Entries/Entries.css" />
}

The resultant HTML page then includes a section that looks like this:

<head>
    <!-- ... Rest of your head section here ... ->
    <link rel="Stylesheet" type="text/css" href="/Entries/Entries.css" />
<head>