Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why Asp.Net MVC 5 put @Scripts.Render("~/bundles/jquery") at the bottom in _Layout.cshtml?

Tags:

I put <script> blocks which use jQuery in the body of one (and only one) cshtml file which uses the template and they causes error because jQuery is not loaded yet.

What's the point to put the @Scripts.Render("~/bundles/jquery") at the bottom of _Layout.cshtml file?

The bottom of the _Layout.cshtml.

    @RenderBody()     <hr />     <footer>     </footer> </div>      @Scripts.Render("~/bundles/jquery")     @Scripts.Render("~/bundles/bootstrap")     @RenderSection("scripts", required: false) </body> </html> 

The following shows the generated source of the cshtml file.

<script>     $(document).ready(function () { /// $ not defined.         // .....     }); </script>      <hr />     <footer>     </footer> </div>  <script src="/Scripts/jquery-1.10.2.js"></script> <script src="/Scripts/bootstrap.js"></script> 
like image 335
ca9163d9 Avatar asked Aug 23 '14 05:08

ca9163d9


People also ask

What is scripts render ~/ bundles Jqueryval?

As you can see above ~/bundles/jqueryval is the virtual path of the bundle which combines the files specified in it. So later on when you see this: @section Scripts { @Scripts.Render("~/bundles/jqueryval") } The above will include the scripts bundled under that reference.

Why are minification and bundling introduced in mvc?

Bundling and minification improves load time by reducing the number of requests to the server and reducing the size of requested assets (such as CSS and JavaScript.)

What is bundling in c#?

Bundling and Minification are two performance improvement techniques that improves the request load time of the application. Most of the current major browsers limit the number of simultaneous connections per hostname to six. It means that at a time, all the additional requests will be queued by the browser.


2 Answers

You can use sections :

in your layout :

... <script src="/Scripts/jquery-1.10.2.js"></script> <script src="/Scripts/bootstrap.js"></script> @RenderSection("scripts", required: false) ... 

in yours cshtml :

@section scripts {     <script>         $(document).ready(function () { /// $ not defined.             // .....         });     </script> } 
like image 78
Pascalz Avatar answered Oct 13 '22 18:10

Pascalz


Just enclose it inside section scripts in .cshtml Page as shown.

@section scripts{   <script>   $(document).ready(function () {      // .....   });   </script> } 
like image 24
Kartikeya Khosla Avatar answered Oct 13 '22 18:10

Kartikeya Khosla