How to add src script inside view when using layout

I want to include a javascript link, for example:

<script src="@Url.Content("~/Scripts/jqueryFoo.js")" type="text/javascript"></script> 

If I have a Razor View, then what is the way to include this without adding it to the layout (I only need it in one specific view, and not in all)

In aspx, we could use content holders. I found older examples using aspx in mvc but not Razor.

+57
asp.net-mvc razor
Jan 11 '13 at 18:47
source share
3 answers

Depending on how you want to implement it (if there was a specific location in which you wanted to use scripts), you could implement @section in your _Layout , which will allow you to add additional scripts from the view itself, while preserving the composition. eg.

_layout

 <!DOCTYPE html> <html> <head> <title>...</title> <script src="@Url.Content("~/Scripts/jquery.min.js")"></script> @RenderSection("Scripts",false/*required*/) </head> <body> @RenderBody() </body> </html> 

View

 @model MyNamespace.ViewModels.WhateverViewModel @section Scripts { <script src="@Url.Content("~/Scripts/jqueryFoo.js")"></script> } 

Otherwise, you are fine. If you don't mind that it is β€œinline” with the view displayed, you can put a <script> declaration in the view.

+96
Jan 11 '13 at 18:52
source share
β€” -

If you use the Razor viewer, edit the _Layout.cshtml file. Move the @ Scripts.Render ("~ / bundles / jquery") located in the footer to the header section and write the javascript / jquery code as you want:

 @Scripts.Render("~/bundles/jquery") <script type="text/javascript"> $(document).ready(function () { var divLength = $('div').length; alert(divLength); }); </script> 
+10
Jan 21 '15 at 7:02
source share

You can add script tags in the same way as we use in asp.net when performing client-side validation, as shown below.

 @{ ViewBag.Title = "Index"; } <h2>Index</h2> <script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script> <script type="text/javascript"> $(function () { //Your code }); </script> 
0
Jun 19 '17 at 17:37 on
source share



All Articles