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?
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")
}
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") }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With