6

In my _Layout.cshtml page I want to only include certain @Styles.Render bundles depending on the view being displayed. For example one page may use the jQueryUI library while another may not and I don't want to make the request to download the library if I don't have to. Can I use a conditional statement in my _layout.cshtml to achieve this?

1
  • 1
    Why don't you use the layout to output the baseline styles/scripts that all views need, and then let the individual views add additional files using a @section? Commented May 22, 2013 at 18:39

2 Answers 2

6

In your _Layout.cshtml page add a @RenderSection

@RenderSection("Page_Styles", required: false)

Then in your individual views you can add styles as needed

@section Page_Styles {
    @Styles.Render("~/bundles/style/foo")
}

Same idea for scripts

@RenderSection("Scripts", required: false)

@section Scripts {
    @Scripts.Render("~/bundles/jqueryui")
}
Sign up to request clarification or add additional context in comments.

Comments

4

You're better off creating a section in your _layout.cshtml file and then adding content to that section within the view itself. I do something like this for my stylesheets that I don't want to load on every single page:

<!-- _layout.cshtml -->
<head>
    <!-- will load on every page -->
    <link rel="stylesheet" href="common.css" />
    <!-- will load on only the views where you have @section CSS -->
    @RenderSection("CSS", false)
</head>

and then the view:

<p>some content</p>
@section CSS { @Styles.Render("~/mystylesheet.css") }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.