简体   繁体   English

为什么ASP.NET MVC无法识别淘汰

[英]Why ASP.NET MVC doesn't recognize knockout

I am trying to use knockout.js in my MVC 4 (Web Api) project, so I added Knockout.js using Managae NuGet Packages, than I added it to the BundleConfig 我试图在我的MVC 4(Web Api)项目中使用knockout.js,因此我使用Managae NuGet软件包添加了Knockout.js,而不是将其添加到BundleConfig

 bundles.Add(new ScriptBundle("~/bundles/knockout").Include(
                    "~/Scripts/knockout-{version}.js"));

I added it in my _Layout.cshtml 我在_Layout.cshtml中添加了它

 @Scripts.Render("~/bundles/knockout")

When I tried to use it in my ViewModel.js - ko.applyBindings(new ViewModel()); 当我尝试在ViewModel.js中使用它时ko.applyBindings(new ViewModel()); it didn't recognize it -> the "word" ko wasn't found...I ignored it and continued to write my code but after running it no comment from the knockout.. What am I missing here? 它无法识别->未找到“单词” ko ...我忽略了它,并继续编写我的代码,但是在运行它后,敲除后没有任何注释..我在这里缺少什么?

You have not shown your code, but I think the problem is quite easy to explain: 您尚未显示代码,但我认为问题很容易解释:

  • by default, MVC renders the bundles in the Scripts section, which is near the bottom of the page 默认情况下,MVC会在页面底部附近的“脚本”部分中呈现包。
  • I bet that you're calling the knockout method inside your templates body. 我敢打赌,您正在模板主体内部调用敲除方法。 What happens is that, at that point, the Scripts are still not included in the page, thus the error message 发生的事情是,到那时,脚本仍未包含在页面中,因此错误消息

You have to change your code, so that, when you call one of the ko method, ko is already loaded. 您必须更改代码,以便在调用ko方法之一时,ko已被加载。 Two possible options (but there are more): 两种可能的选择(但还有更多选择):

  • render the KO bundle on the <head> section of your layout 在布局的<head>部分渲染KO捆绑包
  • call the ko function from inside the jQuery document ready event, like this: 从jQuery文档ready事件内部调用ko函数,如下所示:

    $(document).ready(function() { // Your ko calls here }); $(document).ready(function(){//您的ko在这里打电话});

In fact, the second solution wait to execute the code until all the page has been loaded, and is the recommende way to run any script that interacts with the DOM of the page. 实际上,第二种解决方案要等到所有页面加载完毕后再执行代码,这是运行与页面DOM交互的任何脚本的推荐方法。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM