2015-12-23 43 views
1

我创建了一个新的MVC6空项目。新增bower.json和jQuery依赖MVC 6参考空模板中的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中? 感谢

编辑: enter image description here

当我将鼠标悬停在<script>标签我得到“找不到路径”提示

回答

1

您的代码应该只要罚款,你有文件的jquery.js工作,在该位置。

而且你需要确保你叫Configure()法(内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文件等。

UseStaticFiles()方法

您可以考虑使用environment标签帮助程序将脚本包含在您的页面中以用于不同的配置/环境。

您不需要使用环境标签助手。您可以直接将脚本标签放入布局文件中。但环境帮手允许我们有条件地基于环境呈现脚本。 (精缩捆绑版VS联合国所有精缩版)

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

如果你希望在你的自定义脚本这样,看看this answer

+0

虽然这是非常有用的东西,它不解决问题引用静态内容文件。出于某种原因,wwwroot \ lib \中的任何文件引用都无法从视图中访问。 – ShaneKm

+0

我需要Startup.cs中的任何东西来告诉它从wwwroot \ lib提供文件吗? – ShaneKm

+0

是的。你需要调用'UseStaticFiles()'方法。看到我更新的答案。 – Shyju