How to include js files in the view. ASP.NET MVC 4

后端 未结 5 1971
迷失自我
迷失自我 2020-12-03 13:57

I wonder why my js file work when I call it in the view:

@section Scripts {  


        
相关标签:
5条回答
  • 2020-12-03 14:14

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

    0 讨论(0)
  • 2020-12-03 14:17

    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

    0 讨论(0)
  • 2020-12-03 14:28

    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")
    
    0 讨论(0)
  • 2020-12-03 14:30

    You should Add rendersection to your Layout Page which your view using.

    @RenderSection("scripts", required: false)
    
    0 讨论(0)
  • 2020-12-03 14:32

    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")
    
    0 讨论(0)
提交回复
热议问题