Search code examples
c#.net-coreasp.net-core-mvcrazor-pages

My Index page is not seeing the javascript library I loaded in my shared layout page


I'm trying to use a javascript library in one of my .Net Core 3.1 Razor pages.

So I added these to my _Layout.cshtml page:

<script src="~/lib/jquery/dist/jquery.min.js"></script>
<script src="~/lib/bootstrap/dist/js/bootstrap.bundle.min.js"></script>
<script src="~/js/gameRec/gr.min.js" type="text/javascript"></script>

Then in my Index.cshtml, I am trying to use gr like this:

@page
@model IndexModel
@{
    ViewData["Title"] = "Home page";
}

<head runat="server">
    <script>
        gr.init({
            selector: 'textarea#record',
            height: 500,
            width: 25,
            view_style: 'body { font-size:14px }'
        });
    </script>
</head>

<div class="text-center">
    <h1 class="display-4">GAME PORTAL</h1>
    <p>GAME</p>
    <div id="gameContainer">
        <textarea id="record" asp-for="game" cols="25" rows="3"></textarea>
    </div>
</div>

But it keeps telling me this:

(index):34 Uncaught ReferenceError: gr is not defined

Now I checked, and I know the library is in the correct place.

So Im not sure why my Index page can't find it.

Is there anything else I need to do?

Thanks!


Solution

  • Tag <head should be in Layout

    All you script files should be in layout at the bottom of the body

    <body>
    ......
     <script src="~/js/gameRec/gr.min.js" type="text/javascript"></script>
    </body>
    

    immediately after this add

    @RenderSection("scripts", required: false)
    
    

    and move your custom script in the botom of index file

    @section Scripts {
    
        <script>
    
    ...... your custom script
    
        </script>
    
    }