Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Conditional @Scripts.Render in ASP.net MVC 4

Tags:

asp.net-mvc

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?

like image 779
TheRealDanBiss Avatar asked May 22 '13 18:05

TheRealDanBiss


2 Answers

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")
}
like image 188
Jasen Avatar answered Sep 17 '22 23:09

Jasen


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") }
like image 42
Chris Conway Avatar answered Sep 21 '22 23:09

Chris Conway