Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to add script src inside a View when using Layout

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..

like image 683
dferraro Avatar asked Sep 26 '22 19:09

dferraro


People also ask

Can I add script inside body?

Scripts can be placed in the <body> , or in the <head> section of an HTML page, or in both.

HOW include script in Cshtml?

Go to Views -> Shared -> _Layout. cshtml file and add the render code. Make sure to register the custom javascript file after the jquery bundle since we are going to use jquery inside our js file. Otherwise we will get a jquery error and also register this before the script RenderSection.

Where should script src go?

The script tag should always be used before the body close or at the bottom in HTML file. The Page will load with HTML and CSS and later JavaScript will load.


2 Answers

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.

like image 195
Brad Christie Avatar answered Oct 07 '22 11:10

Brad Christie


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>
like image 13
Dilip Nannaware Avatar answered Oct 07 '22 12:10

Dilip Nannaware