1

I'm new to ASP.NET MVC and I'm working on a project based on an online course. I'm trying to call a js file to run and it's not working. Here is the call at the end of index.cshtml

@section scripts {
    alert("before");
    <script src="~/js/product.js">
        alert("inside");
    </script>
alert("after");
}

I can't get the window.alert message at the beginning of product.js (see screenshot below) to show up on runtime. Any ideas? enter image description here

2
  • 1
    Do you have any error in the network tab in the developer tools of your browser? Commented Sep 23, 2020 at 19:05
  • Thanks, it was a syntax error, i didnt know syntax errors are not shown on js files :) Commented Sep 24, 2020 at 5:07

2 Answers 2

1

Your problem is the src attribute inside your script tag. If there is a src attribute, the code inside the src element will not run; instead, the js file that's linked will run. Remove the src tag, which will be like this change your code to this:

@section scripts {
    alert("before");
    <script>
        alert("inside");
    </script>
alert("after");
}

Now your alert will run.

Sign up to request clarification or add additional context in comments.

Comments

0

If your @RenderSection("scripts") is inside a tag, I would recommend you don't set it up that way, so that you can do the following:

@section scripts {
  <script type="text/javascript">alert("Before");</script>
  <script type="text/javascript" src=".."></script>
  <script type="text/javascript">alert("After");</script>
}

A script tag inside another script tag isn't going to work correctly, so I would recommend place the @RenderSection("scripts") at an appropriate place in the layout, but not inside a script tag, so that you can nest multiple scripts together as needed.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.