Conditional @ Scripts.Render in ASP.net MVC 4

On my _Layout.cshtml page, I want to include only specific @ Styles.Render packages depending on the view being displayed. For example, one page can use the jQueryUI library, and the other cannot, and I do not want the query to load the library if I do not need it. Can I use a conditional statement in my _layout.cshtml to achieve this?

+6
source share
2 answers

On the _Layout.cshtml page _Layout.cshtml enter @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") } 

The same idea for scripts

 @RenderSection("Scripts", required: false) @section Scripts { @Scripts.Render("~/bundles/jqueryui") } 
+5
source

You better create a section in the _layout.cshtml file, and then add content to that section in the view itself. I am doing something similar for my style sheets, which I do not want to load on every 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 view:

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

Source: https://habr.com/ru/post/945619/


All Articles