Foggymood
Foggymood

Reputation: 23

How to add head section in a page that has layout template

I need add specific css file for my page "Index.cshtml" that has layout "_BasicLayout.cshtml".

In ASP.NET WebForms I could do it with ContentPlaceHolder like this:

Master Page:

<head>
    <Link rel="stylesheet" type="text/css" href="common.css" />
    <ContentPlaceHolder ID="Head" />
</head>

Child Page (Layout = Master Page):

<asp:Content ContentPlaceHolderID="Head">
     <Link rel="stylesheet" type="text/css" href="specific.css" />
</asp:Content>

Question:

How to do it in ASP.NET MVC?

Upvotes: 2

Views: 267

Answers (2)

Tim M.
Tim M.

Reputation: 54377

Use an optional section (old but accurate reference).

In the layout:

<head>
    @* things you always want in the head *@
    <title>@ViewBag.Title</title>
    <link rel="Stylesheet" href="~/my-main-stylesheet.css" type="text/css" />

    @* an optional section called "styles" *@
    @RenderSection( "styles", false )
</head>

In your views that need to add a stylesheet(s):

@section styles {
    <link rel="Stylesheet" href="~/another-stylesheet.css" type="text/css" />
}

Upvotes: 1

John Mc
John Mc

Reputation: 2933

In your Layout page put something like this:

@RenderSection("AdditionalStyles", required: false)

Then in your child pages where you want to use it, you can do:

@section AdditionalStyles
{
    @Styles.Render("~/Content/fileupload/css")
}

Upvotes: 2

Related Questions