I wonder why my js file work when I call it in the view:
@section Scripts {
I'm having the same problem. In my Layout.cshtml file I have @RenderSection("Scripts", required: false)
at the bottom before my closing body tag.
In my index.cshtml I have
@section Scripts{
<script src="~/js/ChangeMenuItemColor.js"></script>
}
But it's not working. It was working fine on the homepage before I implemented the shared layout file. Would like to have a better understanding of whats going on here...
you have to add your script in the Bundle config :
public static void RegisterBundles(BundleCollection bundles)
{
bundles.Add(new ScriptBundle("~/bundles/jquery").Include(
"~/Scripts/jquery-{version}.js", "~/Views/Home/script.js"));
this worked for me
It's because .js
files are not accessible in the ~/Views/
folder. You have to enable it.
To enable access to .js
files in the Views folder, you can add the following to your Views' folder's web.config directly under the handlers
tag:
<add name="JavaScriptHandler"
path="*.js"
verb="*"
preCondition="integratedMode"
type="System.Web.StaticFileHandler" />
Alternatively put your script into the ~/Scripts/
folder and reference it like such:
@Scripts.Render("~/Scripts/script.js")
You should Add rendersection to your Layout Page which your view using.
@RenderSection("scripts", required: false)
Its better practice to place your Js file in Script folder and access it from there. You could write this code in view's head to use the js file
@Scripts.Render("~/Scripts/script.js")