Can I link scripts and styles on a page?

Although linking is a neat VS feature, sometimes I want script or css to be available for a specific page. This way, I can make sure that name conflicts and / or overrides are resolved.

Can I link files so that only global and special files are available?

So, for example, let's say I have a page called Cabinet.cshtml . And I also have Cabinet.js and Cabinet.css . On the other hand, I have another page called AdminPanle.cshtml with admin.js and admin.css .

Now I would like these two views to have access only to their respective files, as well as jQuery and jQuery ui. Therefore jQuery must be global.

+5
source share
1 answer

So what's the problem? By default in your BundleConfig.cs you have:

 bundles.Add(new ScriptBundle("~/bundles/jquery").Include( "~/Scripts/jquery-{version}.js")); bundles.Add(new ScriptBundle("~/bundles/jqueryui").Include( "~/Scripts/jquery-ui-{version}.js")); 

So put these bundles in the head of _Layout.cshtml :

 @Scripts.Render("~/bundles/jquery") @Scripts.Render("~/bundles/jqueryui") 

Create 4 more packages:

 //scripts bundles.Add(new ScriptBundle("~/bundles/cabinet").Include( "~/Scripts/Cabinet.js")); bundles.Add(new ScriptBundle("~/bundles/admin").Include( "~/Scripts/admin.js")); //styles bundles.Add(new StyleBundle("~/Content/cabinet").Include("~/Content/Cabinet.css")); bundles.Add(new StyleBundle("~/Content/admin").Include("~/Content/admin.css")); 

Now you can separate these scripts and styles and add them only to the page you need.

I also suggest that it is useful to define 2 sections in the _Layout.cshtml tag in the head tag.

 <head> //other scripts and styles here @RenderSection("scriptslib", required: false) @RenderSection("csslib", required: false) </head> 

So, now in your views ( Cabinet.cshtml and AdminPanle.cshtml ) you can place your libraries where they assumed that they would be like this:

 @section scriptslib{ @Scripts.Render("~/bundles/cabinet") } 
+12
source

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


All Articles