【问题标题】:MVC 6 reference Jquery in empty templateMVC 6 在空模板中引用 Jquery
【发布时间】:2015-12-23 16:27:47
【问题描述】:

我创建了一个新的 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 中? 谢谢

编辑:

当我将鼠标悬停在 &lt;script&gt; 标签上时,我得到“找不到路径”工具提示

【问题讨论】:

    标签: asp.net-core-mvc


    【解决方案1】:

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

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

    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 标签助手将脚本包含到您的页面中以适应不同的配置/环境。

    您不必使用环境标签助手。您可以直接将您的脚本标签放在布局文件中。但是环境助手允许我们根据环境有条件地渲染脚本。 (Minified-Bundled 版本 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>
    

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

    【讨论】:

    • 虽然这很有用,但它并不能解决引用静态内容文件的问题。由于某种原因,无法从视图访问 wwwroot\lib\ 中的任何文件引用。
    • 我需要 Startup.cs 中的任何内容来告诉它从 wwwroot\lib 提供文件吗?
    • 是的。您需要调用UseStaticFiles() 方法。请参阅我的更新答案。
    • 好的,就是这样。我需要有 app.UseStaticFiles();在我的 Startup.cs 之前 app.UseMvc()
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-05-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-18
    相关资源
    最近更新 更多