how to add script src inside a View when using Layout

asp.net MvcRazor

asp.net Mvc Problem Overview


I want to include a javascript reference like:

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

If I have a Razor View, what is the proper way to include this without having to add it to the Layout (I only need it in a single specific View, not all of them)

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

asp.net Mvc Solutions


Solution 1 - asp.net Mvc

Depending how you want to implement it (if there was a specific location you wanted the scripts) you could implement a @section within your _Layout which would enable you to add additional scripts from the view itself, while still retaining structure. e.g.

_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, what you have is fine. If you don't mind it being "inline" with the view that was output, you can place the <script> declaration within the view.

Solution 2 - asp.net Mvc

If you are using Razor view engine then edit the _Layout.cshtml file. Move the @Scripts.Render("~/bundles/jquery") present in 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>

Solution 3 - asp.net Mvc

You can add the script tags like how we use in the asp.net while doing client side validations like 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>

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestiondferraroView Question on Stackoverflow
Solution 1 - asp.net MvcBrad ChristieView Answer on Stackoverflow
Solution 2 - asp.net MvcDilip NannawareView Answer on Stackoverflow
Solution 3 - asp.net MvcSanthosh kumar VadlamaniView Answer on Stackoverflow