空模板中的 MVC 6 引用 Jquery

MVC 6 reference Jquery in empty template

我创建了一个新的 MVC6 空项目。添加了 bower.json 和 jquery 依赖项

bower.json

...
  "dependencies": {
    "jquery": "~2.1.4"

它确实正确地引入了

wwwroot\lib\jquery

然后我在我的 _layout.cshtml 页面上引用了它

<script src="~/lib/jquery/dist/jquery.js"></script>

但是 Intellisense 已将路径加下划线。当在浏览器中打开 > 查看源代码并单击路径时,它会显示一个空白页面,就好像没有找到脚本一样。

此外,当我导航到:http://localhost:57405/lib/jquery/dist/jquery.js 时,它没有找到它

我做错了什么?我需要 app.UseStaticFiles();在 Startup.cs? 谢谢

编辑:

当我将鼠标悬停在 <script> 标签上时,我得到 "Path Not Found" 工具提示

只要您在那个位置有 jQuery.js 文件,您的代码就应该可以正常工作。

您还需要确保在 Configure() 方法中调用了 UseStaticFiles() 方法(在 Startup.cs 中)

public void Configure(IApplicationBuilder app, IHostingEnvironment env,  
                                                             ILoggerFactory loggerFactory)
{
     //Other configuration goes here
     app.UseStaticFiles();  // This enables static file serving from the app.
     app.UseMvc(routes =>
        {
            routes.MapRoute(
                name: "default",
                template: "{controller=Home}/{action=Index}/{id?}");
        });
}

UseStaticFiles() 扩展方法启用静态文件服务,包括 js 文件,css 文件等。

您可以考虑使用 environment 标签助手将脚本包含到您的页面中,以适应不同的 configurations/enviornments。

您不必使用环境标签助手。您可以直接将您的脚本标签放在布局文件中。但是环境助手允许我们根据环境有条件地渲染脚本。 (压缩捆绑版 vs All Un 压缩版)

<environment names="Development">
    <script src="~/lib/jquery/dist/jquery.js"></script>       
</environment>
<environment names="Staging,Production">
    <script src="https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.4.min.js"
            asp-fallback-src="~/lib/jquery/dist/jquery.min.js"
            asp-fallback-test="window.jQuery">
    </script>
</environment>

如果您想以这种方式包含自定义脚本,请查看